index.js (1597B)
1 function E () { 2 // Keep this empty so it's easier to inherit from 3 // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) 4 } 5 6 E.prototype = { 7 on: function (name, callback, ctx) { 8 var e = this.e || (this.e = {}); 9 10 (e[name] || (e[name] = [])).push({ 11 fn: callback, 12 ctx: ctx 13 }); 14 15 return this; 16 }, 17 18 once: function (name, callback, ctx) { 19 var self = this; 20 function listener () { 21 self.off(name, listener); 22 callback.apply(ctx, arguments); 23 }; 24 25 listener._ = callback 26 return this.on(name, listener, ctx); 27 }, 28 29 emit: function (name) { 30 var data = [].slice.call(arguments, 1); 31 var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); 32 var i = 0; 33 var len = evtArr.length; 34 35 for (i; i < len; i++) { 36 evtArr[i].fn.apply(evtArr[i].ctx, data); 37 } 38 39 return this; 40 }, 41 42 off: function (name, callback) { 43 var e = this.e || (this.e = {}); 44 var evts = e[name]; 45 var liveEvents = []; 46 47 if (evts && callback) { 48 for (var i = 0, len = evts.length; i < len; i++) { 49 if (evts[i].fn !== callback && evts[i].fn._ !== callback) 50 liveEvents.push(evts[i]); 51 } 52 } 53 54 // Remove event from queue to prevent memory leak 55 // Suggested by https://github.com/lazd 56 // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 57 58 (liveEvents.length) 59 ? e[name] = liveEvents 60 : delete e[name]; 61 62 return this; 63 } 64 }; 65 66 module.exports = E; 67 module.exports.TinyEmitter = E;