index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. E.prototype = {
  6. on: function (name, callback, ctx) {
  7. var e = this.e || (this.e = {});
  8. (e[name] || (e[name] = [])).push({
  9. fn: callback,
  10. ctx: ctx
  11. });
  12. return this;
  13. },
  14. once: function (name, callback, ctx) {
  15. var self = this;
  16. function listener () {
  17. self.off(name, listener);
  18. callback.apply(ctx, arguments);
  19. };
  20. listener._ = callback
  21. return this.on(name, listener, ctx);
  22. },
  23. emit: function (name) {
  24. var data = [].slice.call(arguments, 1);
  25. var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
  26. var i = 0;
  27. var len = evtArr.length;
  28. for (i; i < len; i++) {
  29. evtArr[i].fn.apply(evtArr[i].ctx, data);
  30. }
  31. return this;
  32. },
  33. off: function (name, callback) {
  34. var e = this.e || (this.e = {});
  35. var evts = e[name];
  36. var liveEvents = [];
  37. if (evts && callback) {
  38. for (var i = 0, len = evts.length; i < len; i++) {
  39. if (evts[i].fn !== callback && evts[i].fn._ !== callback)
  40. liveEvents.push(evts[i]);
  41. }
  42. }
  43. // Remove event from queue to prevent memory leak
  44. // Suggested by https://github.com/lazd
  45. // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
  46. (liveEvents.length)
  47. ? e[name] = liveEvents
  48. : delete e[name];
  49. return this;
  50. }
  51. };
  52. module.exports = E;
  53. module.exports.TinyEmitter = E;