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.
Draw your attention on
dataparameter of theonmethod here: http://api.jquery.com/on/Also you can utilize jQuery.proxy method: http://api.jquery.com/jQuery.proxy/
Here is jsFiddle: jsFiddle