Skip to content

Instantly share code, notes, and snippets.

@felipap
Last active December 29, 2015 17:09
Show Gist options
  • Save felipap/7701812 to your computer and use it in GitHub Desktop.
Save felipap/7701812 to your computer and use it in GitHub Desktop.
Minimalistic backbone-like Javascript events for light usage.
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