Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created March 11, 2015 13:32
Show Gist options
  • Save ismasan/64ec3b7424b33ea38ce6 to your computer and use it in GitHub Desktop.
Save ismasan/64ec3b7424b33ea38ce6 to your computer and use it in GitHub Desktop.
Simplified events emitter (JS)
/**
* Simple event dispatcher
*
* Example
*
* var MyConstructor = function () {
* var self = this
* var count = 0
* setInterval(function () {
* self.emit('tick', {count: count})
* count++
* }, 2000)
* }
* MyConstructor.prototype = new Events()
*
* var instance = new MyConstructor()
* instance.on('tick', function (data) {
* console.log('Tock!', data)
* })
*/
var Events = (function () {
var Events = function () {
this._handlers = {}
}
Events.prototype = {
on: function (eventName, handlerFunc) {
this._handlers[eventName] = this._handlers[eventName] || []
this._handlers[eventName].push(handlerFunc)
return this
},
emit: function (eventName, data) {
if(!this._handlers[eventName]) return this
this._handlers[eventName].forEach(function (handler) {
handler(data)
})
return this
}
}
return Events
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment