Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass additional arguments to event handler? [duplicate]

I have my functions defined in an object like this:

_clickHandler: function(event){
  event.preventDefault();

},

attachClickEv: function(element){
  ......
  element.on('click', this._clickHandler);
},

The problem is that I cannot seem to pass "this" to the clickHandler function

I know that I could wrap that in another function like:

var tthis = this;
element.on('click', function(event){
  tthis._clickHandler(event, tthis);
});

but then I cannot unhook the function later with:

element.off('click', this._clickHandler);

Is there any other way to do it?

like image 943
Alex Avatar asked Nov 30 '22 18:11

Alex


2 Answers

You can use bind for that. Here is an example:

element.on('click', this._clickHandler.bind(this));

//later in the code...

_clickHandler: function(event) {

}

Since you're using jQuery though, you can also use jQuery.proxy() too. More here: http://api.jquery.com/jQuery.proxy

Update:

To get access to the element inside the callback you would have to use event.target or event.currentTarget or do the following (depends on what you're doing):

element.on('click', this._clickHandler.bind(this, element));

//later in the code...

_clickHandler: function(element, event) {

}

Another way is to set the element as a property of the object like: this.element = $('#el') and then use that in your callback(s).

Live example: http://jsbin.com/mezuberucu/1/edit?html,js,output

like image 192
istos Avatar answered Dec 04 '22 09:12

istos


_clickHandler: function(x, y, event){
  // x = 1, y = 2
  event.preventDefault();
},

attachClickEv: function(element){
  element.on('click', this._clickHandler.bind(1,2));
},
like image 21
vadimtar Avatar answered Dec 04 '22 09:12

vadimtar