我认为 JS 范围不会再让我感到惊讶,但我们来了。
我正在使用这个 little JQuery plugin for observer like pattern . 这就是我从自定义事件订阅和取消订阅处理程序(监听器)的方式
$.observer.subscribe('my-event', this.myHandler);
$.observer.unsubscribe('my-event', this.myHandler);
public myHandler() {
console.log("hello World", this);
}
问题是,如果我使用类方法作为回调 (this.myHandler
),该方法将不会在类范围内调用,而是在观察者对象范围内调用。
当我像这样使用 JQuery 的代理方法时:
$.observer.subscribe('my-event', $.proxy(this.myHandler, this));
$.observer.unsubscribe('my-event', $.proxy(this.myHandler, this));
处理程序中的范围是正确的,但取消订阅方法停止工作,显然我正在取消订阅其他东西的代理,而不是处理程序方法。
我不能使用定义局部变量的旧 JS 技巧,而是使用它来代替这个,比如
var o = this;
public myHandler() {
console.log("hello World", o);
}
因为这是一个 typescript 类,var 有不同的含义。
我该怎么办?
最佳答案
发生这种情况的原因是因为 $.proxy(this.myHandler, this)
每次调用它时都会返回一个新函数。为了使 unsubscribe
正常工作,您需要将传递给 subscribe
的相同函数传递给它(几乎所有监听器接口(interface)都是这种情况,包括 DOM 接口(interface))。
const handler = $.proxy(this.myHandler, this);
$.observer.subscribe('my-event', handler);
$.observer.unsubscribe('my-event', handler);
或者,您可以在构造函数中将方法创建为箭头函数属性,或者自动绑定(bind)它:
class YourClass {
constructor() {
this.myHandler = () => {};
// or
this.myHandler = this.myHandler.bind(this);
}
}
然后您只需将 this.myHandler
传递给 observer.subscribe
,它就会执行正确的操作。
关于javascript - TypeScript 类和 JS 范围混淆(再次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39450342/