You have to give up yours. Here is just one way.
var MyClass = function() { this._events = {}; }; MyClass.prototype = { addListener: function(eventName, callback) { var events = this._events, callbacks = events[eventName] = events[eventName] || []; callbacks.push(callback); }, raiseEvent: function(eventName, args) { var callbacks = this._events[eventName]; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i].apply(null, args); } }, test : function() { this.raiseEvent('ON_TEST', [1,2,3]);
You should probably also add a โremoveListenerโ that would have to find the callback in the array and remove it from the array (or perhaps remove all listeners for the whole event if no callback is specified).
Infinitiesloop
source share