Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created August 12, 2014 06:42
Show Gist options
  • Save benshimmin/f2380af7207ad9e49a1b to your computer and use it in GitHub Desktop.
Save benshimmin/f2380af7207ad9e49a1b to your computer and use it in GitHub Desktop.
Make any function have "on", "off", and "trigger" functionality
// Put this in a utility file somewhere. (Requires Underscore.)
var Eventable = {
on : function(event, callback) {
this.events[event] = callback;
return this;
},
off : function(event) {
delete this.events[event];
return this;
},
trigger : function(event, data) {
if (_.has(this.events, event)) {
this.events[event].apply(this, [data]);
}
return this;
},
eventable : function(scope) {
scope.events = scope.events || {};
_.bindAll(scope, "on", "off", "trigger");
}
};
function MySomething() {
this.eventable(this);
}
_.extend(MySomething.prototype, Eventable);
// elsewhere:
var s = new MySomething();
s.on("something", function() {
console.log("Something called!");
});
s.trigger("something"); // -> "Something called!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment