function PubSub() { this._event = {}; this.on = function (eventName, handler) { if (this._event[eventName]) { this._event[eventName].push(handler); } else { this._event[eventName] = [handler]; } }; this.emit = function (eventName) { var events = this._event[eventName]; var otherArgs = Array.prototype.slice.call(arguments).slice(1); var self = this; if (events) { events.forEach(function (event) { event.apply(self, otherArgs); }); } }; this.off = function (eventName, handler) { var events = this._event[eventName]; if (events) { this._event[eventName] = events.filter(function (event) { return event !== handler; }); } }; this.once = function (eventName, handler) { var self = this; function func() { var args = Array.prototype.slice.call(arguments); handler.apply(self, args); this.off(eventName, func); } this.on(eventName, func); }; this.removeAll = function removeAll(eventName) { delete this._event[eventName]; }; } // ES6 class PubSub { constructor() { this._event = {}; } on(eventName, handler) { if (this._event[eventName]) { this._event[eventName].push(handler); } else { this._event[eventName] = [handler]; } } emit(eventName) { const events = this._event[eventName]; const otherArgs = [...arguments].slice(1); const self = this; if (events) { events.forEach(event => { event.apply(self, otherArgs); }); } } off(eventName, handler) { const events = this._event[eventName]; if (events) { this._event[eventName] = events.filter(event => { return event !== handler; }); } } once(eventName, handler) { const self = this; function func() { const args = [...arguments]; handler.apply(self, args); this.off(eventName, func); } this.on(eventName, func); } removeAll(eventName){ delete this._event[eventName]; } }