Last active
December 29, 2015 17:09
-
-
Save felipap/7701812 to your computer and use it in GitHub Desktop.
Minimalistic backbone-like Javascript events for light usage.
This file contains hidden or 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
function implementEvents() { | |
this._callbacks = {}; | |
this.on = function (eventName, func, t) { | |
if (typeof func !== 'function') | |
throw "Invalid argument to .on() "+func | |
if (this._callbacks[eventName]) | |
this._callbacks[eventName].push(t?func.bind(t):func); | |
else | |
this._callbacks[eventName] = [t?func.bind(t):func]; | |
} | |
this.trigger = function (eventName, args) { | |
var funcs = this._callbacks[eventName]; | |
if (!funcs) | |
return false; | |
for (var i=0; i<funcs.length; i++) { | |
funcs[i].apply(this, args); // Bind to this or entered object (arg 't' in this.on) | |
} | |
return i; | |
} | |
} | |
// Usage: | |
var obj = new (function () { | |
// ... | |
implementEvents.bind(this)(); | |
// ... | |
})(); | |
// then... | |
obj.on('change', this.change, this); | |
obj.on('change', obj.render); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment