event.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. class Event {
  2. on(event, fn, ctx) {
  3. if (typeof fn !== 'function') {
  4. console.error('listener must be a function');
  5. return;
  6. }
  7. this._stores = this._stores || {};
  8. (this._stores[event] = this._stores[event] || []).push({
  9. cb: fn,
  10. ctx: ctx
  11. });
  12. }
  13. emit(event) {
  14. this._stores = this._stores || {};
  15. let store = this._stores[event];
  16. let args;
  17. if (store) {
  18. store = store.slice(0);
  19. args = [].slice.call(arguments, 1), args[0] = {
  20. eventCode: event,
  21. data: args[0]
  22. };
  23. for (let i = 0, len = store.length; i < len; i++) {
  24. store[i].cb.apply(store[i].ctx, args);
  25. }
  26. }
  27. }
  28. off(event, fn) {
  29. this._stores = this._stores || {}; // all
  30. if (!arguments.length) {
  31. this._stores = {};
  32. return;
  33. } // specific event
  34. const store = this._stores[event];
  35. if (!store) return; // remove all handlers
  36. if (arguments.length === 1) {
  37. delete this._stores[event];
  38. return;
  39. } // remove specific handler
  40. let cb;
  41. for (let i = 0, len = store.length; i < len; i++) {
  42. cb = store[i].cb;
  43. if (cb === fn) {
  44. store.splice(i, 1);
  45. break;
  46. }
  47. }
  48. return;
  49. }
  50. }
  51. module.exports = Event;