Created
March 11, 2015 13:32
-
-
Save ismasan/64ec3b7424b33ea38ce6 to your computer and use it in GitHub Desktop.
Simplified events emitter (JS)
This file contains 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
/** | |
* 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