-
-
Save tjmw/fcd610af1e2feaf401b6 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