问题
I have the following function:
onDocumentKeyUp: function (e) {
if (e.keyCode === 27) {
this.deactivate();
}
}
I wanted to bind this like so:
$(document).on('keyup', onDocumentKeyUp);
However, when I do that, the this
inside the onDocumentKeyUp
function refers to the document. I solved this by doing:
var self = this;
$(document).on('keyup', function(e) { self.onDocumentKeyUp(e); });
This works, but something tells me there's a cleaner way to pull this off. Would .call()
or .apply()
somehow..apply here? I'm still unsure how those functions work exactly.
Also, I don't necessarily need to limit myself to jQuery.on()
. If there is a 'vanilla' way of doing this, be my guest to teach me.
回答1:
Draw your attention on data
parameter of the on
method here: http://api.jquery.com/on/
Also you can utilize jQuery.proxy method: http://api.jquery.com/jQuery.proxy/
Here is jsFiddle: jsFiddle
回答2:
You can use .bind() to set the context (without immediately calling it like call
or apply
):
$(document).on('keyup', this.onDocumentKeyUp.bind(this));
As this method is only supported by ES5.1-compliant browsers, you might use jQuery.proxy instead of polyfilling it.
来源:https://stackoverflow.com/questions/12949155/maintaining-the-value-of-this-when-using-event-listener