ekimpl
ekimpl

Reputation: 521

jQuery widget call private function from event handler

I have a jQuery ui widget which has a link in it's content

 <a href="test" data-foo="clickThis">Click me</a>

in _create function I attach click event handler and create instance variable

_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
}

I have multiple instances of widget on one page, so each one should access it's own instanceVariable. One way I found to do this, is to pass this as event.data to the click handler, however I don't like this solution, as this is just some workaround.

this.$elem.on('click', 'a[data-foo]', this, this._clickHandler);

I would appreciate some better solution.

Upvotes: 4

Views: 1851

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

You can pass a custom execution context to the click handler using $.proxy() then this inside the event handler will point to the widget so you can call this._otherPrivateFunction() from the handler method

this.$elem.on('click', 'a[data-foo]', $.proxy(this._clickHandler, this));

Upvotes: 6

Related Questions