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?
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
_clickHandler: function(x, y, event){
// x = 1, y = 2
event.preventDefault();
},
attachClickEv: function(element){
element.on('click', this._clickHandler.bind(1,2));
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With