Javascript solution:
function Dispatcher(){
"use strict";
this.listeners = [];
/* public function dispatch
* @Description: Execute the callback subscribed to an event.
* @Arguments: eventName
* @Return: void;
*/
this.trigger = function (eventName, eventData) {
if(this.listeners[eventName]) {
for(var i=0; i < this.listeners[eventName].length; i++) {
this.listeners[eventName][i].callback(eventData);
if(this.listeners[eventName][i].executeOnce) {
this.listeners[eventName].splice(i, 1);
}
}
}
};
/* public function on()
* @Description: Subscribe the callback to certain event
* @Arguments: eventName, callback, executeOnce.
* @Return void;
*/
this.on = function(eventName, callback, executeOnce) {
var listener = {
callback: callback,
executeOnce: executeOnce
};
if(!this.listeners[eventName]) { this.listeners[eventName] = []; }
this.listeners[eventName].push(listener);
};
/* public function off()
* @Description: Un-subscribe all the callbacks subscribed to certain event.
* @Arguments: eventName
* @Return void;
*/
this.off = function(eventName) {
if(this.listeners[eventName]) {
delete this.listeners[eventName];
}
};
/* public function one()
* @Description: Subscribe the callback to be executed only once to the eventName
* @Arguments: eventName, callback
* @Return void;
*/
this.one = function(eventName, callback) {
this.on(eventName, callback, true);
};
}
var dispatcher = new Dispatcher();
dispatcher.one('customEvent', function(eventData) {
console.log('customEventFired');
});
dispatcher.one('customEvent', function(eventData) {
console.log('another action that depends on this event');
});
dispatcher.trigger('customEvent');
dispatcher.trigger('customEvent');
$("a").on("click", function(){});