I ma trying to have my custom javascript objects be able to dispatch thier own events. I have this code exmaple. The problem is that events are duplicated when I create more than 1 object. Why is this hapenning?
(function() {
var EventDispatcher = function() {
var self = this;
self.events = {};
self.addEventListener = function(name, handler) {
if (self.events.hasOwnProperty(name)) {
self.events[name].push(handler);
} else {
self.events[name] = [handler];
}
};
self.removeEventListener = function(name, handler) {
if (!self.events.hasOwnProperty(name)) return;
var index = self.events[name].indexOf(handler);
if (index != -1) self.events[name].splice(index, 1);
};
self.fireEvent = function(name, args) {
if (!self.events.hasOwnProperty(name)) return;
if (!args || !args.length) args = [];
var evs = self.events[name],
l = evs.length;
for (var i = 0; i < l; i++) {
evs[i].apply(null, args);
}
};
};
window.EventDispatcher = EventDispatcher;
}(window));
(function(window) {
"use strict"
var PlaylistManager = function(data) {
var self = this
this.test = function() {
self.fireEvent('PlaylistManager.COUNTER_READY', [{
counter: "a"
}]);
}
}
PlaylistManager.prototype = new EventDispatcher();
window.PlaylistManager = PlaylistManager;
}(window));
var _PlaylistManager = new PlaylistManager();
_PlaylistManager.addEventListener('PlaylistManager.COUNTER_READY', function(e) {
console.log('COUNTER_READY')
})
var _PlaylistManager2 = new PlaylistManager();
_PlaylistManager2.addEventListener('PlaylistManager.COUNTER_READY', function(e) {
console.log('COUNTER_READY 2')
})
_PlaylistManager.test()
_PlaylistManager2.test()
Comments
Post a Comment