Created
August 12, 2014 06:42
-
-
Save benshimmin/f2380af7207ad9e49a1b to your computer and use it in GitHub Desktop.
Make any function have "on", "off", and "trigger" functionality
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
// 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"); | |
} | |
}; |
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 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