Last active
December 26, 2015 02:49
-
-
Save alexandrusavin/7081887 to your computer and use it in GitHub Desktop.
Simplified event dispatcher for in browser javascript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Ex: | |
* | |
* Object = function () {} | |
* Object.prototype = new AbstractEventsDispatcher; | |
* | |
* Object.trigger("event", arguments); | |
*/ | |
var AbstractEventsDispatcher = function () { | |
}; | |
AbstractEventsDispatcher.prototype = { | |
callbacks: {}, | |
global_callbacks: [], | |
bind: function (event_name, callback) { | |
this.callbacks[event_name] = this.callbacks[event_name] || []; | |
this.callbacks[event_name].push(callback); | |
return this;// chainable | |
}, | |
trigger: function () { | |
var args = Array.slice(arguments); | |
this.dispatch.apply(this, args); | |
this.dispatch_global.apply(this, args); | |
return this; | |
}, | |
bind_all: function (callback) { | |
this.global_callbacks.push(callback); | |
return this; | |
}, | |
bind_all_except: function (except, handler) { | |
this.bind_all(function (event_name, event_data) { | |
if (except.indexOf(event_name) > -1) return false; | |
handler(event_name, event_data) | |
}); | |
return this | |
}, | |
dispatch: function () { | |
var event_name = arguments[0]; | |
var args = Array.slice(arguments); | |
args.shift(); | |
var chain = this.callbacks[event_name]; | |
if (typeof chain == 'undefined') return; // no callbacks for this event | |
for (var i = 0; i < chain.length; i++) { | |
chain[i].apply(this, args); | |
} | |
}, | |
dispatch_global: function () { | |
var args = Array.slice(arguments); | |
args.shift(); | |
for (var i = 0; i < this.global_callbacks.length; i++) { | |
this.global_callbacks[i].apply(this, args); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment