EventListener.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const EventListener = function (obj) {
  2. let Register = {};
  3. obj.on = function (name, target, method) {
  4. if (!Register.hasOwnProperty(name)) {
  5. Register[name] = [];
  6. }
  7. let event = {};
  8. event["target"] = target;
  9. event["methods"] = method;
  10. Register[name].push(event);
  11. };
  12. obj.fire = function (name) {
  13. if (Register.hasOwnProperty(name)) {
  14. let eventArray = Register[name];
  15. for (let i = 0; i < eventArray.length; i++) {
  16. let event = eventArray[i];
  17. let handler = event["methods"];
  18. let target = event["target"];
  19. let args = [];
  20. for (let j = 1; j < arguments.length; j++) {
  21. args.push(arguments[j]);
  22. }
  23. /*
  24. * JavaScript 的函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念
  25. * apply的功能: 当一个 object 没有某个方法, 但是其他的有,我们可以借助call或apply用其它对象的方法来操作
  26. * call 和 apply 的区别:
  27. * - 作用完全一样,只是接受参数的方式不太一样
  28. * - call 需要把参数按顺序传递进去,而 apply 则是把参数放在数组里
  29. */
  30. handler.apply(target, args);
  31. }
  32. }
  33. };
  34. obj.off = function (name, target) {
  35. if (Register.hasOwnProperty(name)) {
  36. let eventArray = Register[name];
  37. for (let i = 0; i < eventArray.length; i++) {
  38. let event = eventArray[i];
  39. let eventTarget = event["target"];
  40. if (target === eventTarget) {
  41. eventArray.splice(i, 1);
  42. }
  43. }
  44. }
  45. };
  46. return obj;
  47. };
  48. export default EventListener;