6 if (typeof module !== 'undefined') {
\r
7 module.exports = Emitter;
\r
11 * Initialize a new `Emitter`.
\r
16 function Emitter(obj) {
\r
17 if (obj) return mixin(obj);
\r
21 * Mixin the emitter properties.
\r
23 * @param {Object} obj
\r
28 function mixin(obj) {
\r
29 for (var key in Emitter.prototype) {
\r
30 obj[key] = Emitter.prototype[key];
\r
36 * Listen on the given `event` with `fn`.
\r
38 * @param {String} event
\r
39 * @param {Function} fn
\r
44 Emitter.prototype.on =
\r
45 Emitter.prototype.addEventListener = function(event, fn){
\r
46 this._callbacks = this._callbacks || {};
\r
47 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
\r
53 * Adds an `event` listener that will be invoked a single
\r
54 * time then automatically removed.
\r
56 * @param {String} event
\r
57 * @param {Function} fn
\r
62 Emitter.prototype.once = function(event, fn){
\r
64 this.off(event, on);
\r
65 fn.apply(this, arguments);
\r
74 * Remove the given callback for `event` or all
\r
75 * registered callbacks.
\r
77 * @param {String} event
\r
78 * @param {Function} fn
\r
83 Emitter.prototype.off =
\r
84 Emitter.prototype.removeListener =
\r
85 Emitter.prototype.removeAllListeners =
\r
86 Emitter.prototype.removeEventListener = function(event, fn){
\r
87 this._callbacks = this._callbacks || {};
\r
90 if (0 == arguments.length) {
\r
91 this._callbacks = {};
\r
96 var callbacks = this._callbacks['$' + event];
\r
97 if (!callbacks) return this;
\r
99 // remove all handlers
\r
100 if (1 == arguments.length) {
\r
101 delete this._callbacks['$' + event];
\r
105 // remove specific handler
\r
107 for (var i = 0; i < callbacks.length; i++) {
\r
109 if (cb === fn || cb.fn === fn) {
\r
110 callbacks.splice(i, 1);
\r
115 // Remove event specific arrays for event types that no
\r
116 // one is subscribed for to avoid memory leak.
\r
117 if (callbacks.length === 0) {
\r
118 delete this._callbacks['$' + event];
\r
125 * Emit `event` with the given args.
\r
127 * @param {String} event
\r
128 * @param {Mixed} ...
\r
129 * @return {Emitter}
\r
132 Emitter.prototype.emit = function(event){
\r
133 this._callbacks = this._callbacks || {};
\r
135 var args = new Array(arguments.length - 1)
\r
136 , callbacks = this._callbacks['$' + event];
\r
138 for (var i = 1; i < arguments.length; i++) {
\r
139 args[i - 1] = arguments[i];
\r
143 callbacks = callbacks.slice(0);
\r
144 for (var i = 0, len = callbacks.length; i < len; ++i) {
\r
145 callbacks[i].apply(this, args);
\r
153 * Return array of callbacks for `event`.
\r
155 * @param {String} event
\r
160 Emitter.prototype.listeners = function(event){
\r
161 this._callbacks = this._callbacks || {};
\r
162 return this._callbacks['$' + event] || [];
\r
166 * Check if this emitter has `event` handlers.
\r
168 * @param {String} event
\r
169 * @return {Boolean}
\r
173 Emitter.prototype.hasListeners = function(event){
\r
174 return !! this.listeners(event).length;
\r