Maintaining the value of 'this' when using event listener

前端 未结 2 1298
太阳男子
太阳男子 2021-01-25 12:22

I have the following function:

onDocumentKeyUp: function (e) {
    if (e.keyCode === 27) {
       this.deactivate();
    }
}

I wanted to bind t

相关标签:
2条回答
  • 2021-01-25 12:59

    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.

    0 讨论(0)
  • 2021-01-25 13:09

    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

    0 讨论(0)
提交回复
热议问题