Maintaining the value of 'this' when using event listener

前端 未结 2 1330
太阳男子
太阳男子 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.

提交回复
热议问题