Introducing the EventDispatcher with AliasPicker

/** * Custom Event equivalent */ function CustomEvent() { } CustomEvent.prototype = { type : 'custom' } // Custom EventTarget equivalent function EventDispatcher() { } EventDispatcher.prototype = { // An object literal to store arrays of listeners by type events : {}, // If it supports the type, add the listener (capture ignored) addEventListener : function(type, listener, capture) { if (this.events[type]) { this.events[type].push(listener); } }, // If it supports the type, remove the listener (capture ignored) removeEventListener : function(type, listener, capture) { if (this.events[type] == undefined) { return; } var index = this.events[type].indexOf(listener); if (this.events[type][index]) { this.events[type].splice(index, 1); } }, // Cycle through all of the event listeners, passing the event to the callbacks dispatchEvent : function(type, event) { if (this.events[type]) { for (var i in this.events[type]) { if (typeof this.events[type][i] == 'function') { this.events[type][i](event); // Accepts an array of the contextual object and the function to call } else if (typeof this.events[type][i] == 'object') { this.events[type][i][1].call(this.events[type][i][0], event); } } } } } /** * Extend the CustomEvent class with a specific type * and an extra variable to send the name with the event. */ function NameEnteredEvent(name) { this.type = 'pick'; this.name = name; } NameEnteredEvent.prototype = new CustomEvent; /** * Extend EventDispatcher, creating a 'pick' event. */ function AliasPicker() { this.events.pick = new Array(); } AliasPicker.prototype = new EventDispatcher; /** * The Watcher, in this case, simply defines a callback */ function Watcher() { this.namePicked = function(e) { alert(e.name); } } var picker = new AliasPicker(); var w = new Watcher(); picker.addEventListener('pick', w.namePicked, false); picker.dispatchEvent(new NameEnteredEvent('Bob')); function dispatchIt() { var newValue = document.getElementById("text").value; if (newValue) picker.dispatchEvent.apply(picker, ['pick',new NameEnteredEvent(newValue)]); }