我正在侦听文件输入中的更改,并且每次需要“监听”某些内容后,都需要删除该侦听器。
问题在于,使用命名函数(无法删除匿名函数上的侦听器)时,我失去了上下文,因此无法访问状态。这是基本版本:
$ImgEl.on('change', () => {
const reader = new FileReader();
reader.onloadend = (e) => {
// Do some stuff with state
this.state.whatever;
}
}
Run Code Online (Sandbox Code Playgroud)
通过将此代码与箭头功能配合使用,我可以维护上下文并因此可以访问自己的状态。但是,如果使用命名函数,则可以删除监听器,但会丢失上下文。
还有其他人处理过吗?
这与命名函数与匿名函数无关。重要的是您是否引用了该功能。
如果要删除change处理程序,例如:
// *** Create the function and remember a reference to it
const handler = () => {
const reader = new FileReader();
reader.onloadend = (e) => {
// Do some stuff with state
this.state.whatever;
// Remove it
$ImgEl.off('change', handler); // *** Remove the handler
}
};
$ImgEl.on('change', handler); // *** Hook up the handler
Run Code Online (Sandbox Code Playgroud)
碰巧的是,它确实创建了一个命名函数,但是即使它创建了一个匿名函数,也没关系,因为您需要对其进行引用。
您似乎正在使用jQuery,所以我还要提到事件名称空间,您无需引用该函数即可将其删除,请参见.foo以下内容:
$ImgEl.on('change.foo', () => {
const reader = new FileReader();
reader.onloadend = (e) => {
// Do some stuff with state
this.state.whatever;
// Remove the handler
$ImgEl.off('change.foo');
}
});
Run Code Online (Sandbox Code Playgroud)
我会将该版本与函数引用一起使用,但是您可以选择。:-)
| 归档时间: |
|
| 查看次数: |
22 次 |
| 最近记录: |