Maintaining the value of 'this' when using event listener

做~自己de王妃 提交于 2019-12-20 05:12:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!