jQuery 小部件从事件处理程序调用私有函数

eki*_*mpl 3 javascript jquery widget

我有一个 jQuery ui 小部件,它的内容中有一个链接

 <a href="test" data-foo="clickThis">Click me</a>
Run Code Online (Sandbox Code Playgroud)

_create函数中我附加点击事件处理程序并创建实例变量

_create: function () {
   //*this* here refers to widget
   this.$elem.on('click', 'a[data-foo]', this._clickHandler);
   this.instanceVariable = "someValue";
}

_clickHandler: function (event) {
   //**this** in here refers to link, not to widget
   //Question: How to call _otherPrivateFunction from here 
}

_otherPrivateFunction(){
  //I want to access this.instanceVariable in here
}
Run Code Online (Sandbox Code Playgroud)

我在一页上有多个小部件实例,所以每个实例都应该访问它自己的 instanceVariable。我发现这样做的一种方式,是通过thisevent.data到单击处理程序,但我不喜欢这样的解决方案,因为这只是一些解决方法。

this.$elem.on('click', 'a[data-foo]', this, this._clickHandler);
Run Code Online (Sandbox Code Playgroud)

我会很感激一些更好的解决方案。

Aru*_*hny 5

您可以使用$.proxy()将自定义执行上下文传递给单击处理程序,然后this在事件处理程序内部将指向小部件,以便您可以this._otherPrivateFunction()从处理程序方法调用

this.$elem.on('click', 'a[data-foo]', $.proxy(this._clickHandler, this));
Run Code Online (Sandbox Code Playgroud)