EventListener.js 885 B

1234567891011121314151617181920212223242526272829303132333435
  1. var EventListener = (function () {
  2. let _this = {};
  3. var handlers = {};
  4. // 订阅事件
  5. _this.on = function (eventType, method) {
  6. handlers[eventType] = handlers[eventType] || []
  7. handlers[eventType].push(method);
  8. };
  9. // 触发事件(发布事件)
  10. _this.emit = function (eventType, data) {
  11. if (!handlers[eventType]) {
  12. return
  13. }
  14. for (var i = 0, len = handlers[eventType].length; i < len; i++) {
  15. handlers[eventType][i].call(null, data)
  16. }
  17. };
  18. // 删除订阅事件
  19. _this.off = function (eventType, method) {
  20. let handler = handlers[eventType];
  21. for (var i = 0, len = handler.length; i < len; i++) {
  22. if (handler[i] === method) {
  23. handler.splice(i, 1);
  24. }
  25. }
  26. }
  27. return _this;
  28. }());
  29. module.exports = EventListener;