Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
ekimpl Avatar asked Oct 18 '25 13:10

ekimpl


1 Answers

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));
like image 74
Arun P Johny Avatar answered Oct 20 '25 02:10

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!