event.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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({ cb: fn, ctx: ctx })
  9. }
  10. emit(event) {
  11. this._stores = this._stores || {}
  12. let store = this._stores[event]
  13. let args
  14. if (store) {
  15. store = store.slice(0)
  16. args = [].slice.call(arguments, 1),
  17. args[0] = {
  18. eventCode: event,
  19. data: args[0],
  20. }
  21. for (let i = 0, len = store.length; i < len; i++) {
  22. store[i].cb.apply(store[i].ctx, args)
  23. }
  24. }
  25. }
  26. off(event, fn) {
  27. this._stores = this._stores || {}
  28. // all
  29. if (!arguments.length) {
  30. this._stores = {}
  31. return
  32. }
  33. // specific event
  34. const store = this._stores[event]
  35. if (!store) return
  36. // remove all handlers
  37. if (arguments.length === 1) {
  38. delete this._stores[event]
  39. return
  40. }
  41. // remove specific handler
  42. let cb
  43. for (let i = 0, len = store.length; i < len; i++) {
  44. cb = store[i].cb
  45. if (cb === fn) {
  46. store.splice(i, 1)
  47. break
  48. }
  49. }
  50. return
  51. }
  52. }
  53. module.exports = Event