在 ES6 中添加和删除事件和方法
Adding and removing events and methods in ES6
在 ES6 class 中,如果我像这样添加和删除事件:
viewer.addEventListener(
SELECTION_CHANGED_EVENT,
(e) => this.onFoo(e));
viewer.removeEventListener(
SELECTION_CHANGED_EVENT,
(e) => this.onFoo(e));
事件已添加,但未被删除,但如果像这样添加事件:
在构造函数中:
this.onFooHandler = (e) => this.onFoo(e);
并添加和删除它们:
viewer.addEventListener(
SELECTION_CHANGED_EVENT,
this.onFooHandler);
viewer.removeEventListener(
SELECTION_CHANGED_EVENT,
this.onFooHandler);
它们的添加和删除都很好,但这是为什么呢?有什么区别?
备注:
我使用 Babel 转译代码。
viewer
是一些有事件的对象。
(e) => this.onFoo(e)
是一个总是创建新函数的表达式。
((e) => this.onFoo(e)) === ((e) => this.onFoo(e)) // false
您需要维护原始函数的句柄。
const foo = (e) => this.onFoo(e);
foo === foo; // true
您需要将您在addEventListener
中注册的回调函数再次传递给removeEventListener
。它必须是确切的函数,不仅仅是看起来像的函数。 因为您使用的是匿名回调,所以每个函数都是不同的函数。如果您只创建一次函数并将其分配给一个变量,那么您在两种情况下都使用相同的函数。
在 ES6 class 中,如果我像这样添加和删除事件:
viewer.addEventListener(
SELECTION_CHANGED_EVENT,
(e) => this.onFoo(e));
viewer.removeEventListener(
SELECTION_CHANGED_EVENT,
(e) => this.onFoo(e));
事件已添加,但未被删除,但如果像这样添加事件:
在构造函数中:
this.onFooHandler = (e) => this.onFoo(e);
并添加和删除它们:
viewer.addEventListener(
SELECTION_CHANGED_EVENT,
this.onFooHandler);
viewer.removeEventListener(
SELECTION_CHANGED_EVENT,
this.onFooHandler);
它们的添加和删除都很好,但这是为什么呢?有什么区别?
备注:
我使用 Babel 转译代码。
viewer
是一些有事件的对象。
(e) => this.onFoo(e)
是一个总是创建新函数的表达式。
((e) => this.onFoo(e)) === ((e) => this.onFoo(e)) // false
您需要维护原始函数的句柄。
const foo = (e) => this.onFoo(e);
foo === foo; // true
您需要将您在addEventListener
中注册的回调函数再次传递给removeEventListener
。它必须是确切的函数,不仅仅是看起来像的函数。 因为您使用的是匿名回调,所以每个函数都是不同的函数。如果您只创建一次函数并将其分配给一个变量,那么您在两种情况下都使用相同的函数。