$.on()方法和addEventListener改变this指向

2022-10-22,,,

jquery $.on()方法和addeventlistener改变this指向

标签(空格分隔): jquery javascript


jquery

jq的绑定事件使用$([selector]).on([types], [selector], [data], [fn], [one])方法;解绑事件使用off,但是解绑具体事件时候handler只能是具名函数。

在一个对象中,当我们想要在具名函数中用this访问当前对象的属性,可以从[data]参数传入,然后在具名函数中通过e.data来访问:

var obj = {
    options: { a: 1 },
    init: function() {
        $(window).off('click', this._event);
        $(window).on('click', { self: this }, this._event);
    },
    _event: function(e) {
        var self = e.data.self;
        console.log(self.options);
    }
};

addeventlistener

详细内容参见mdn。
addeventlistener兼容性

1. 通过bind(this)方法

var foo = function (ele) {
    this.name = 'this is foo';
    this.onclicka = function (e) {
        console.log(this.name); // undefined
    };
    this.onclickb = function (e) {
        console.log(this.name); // this is foo
    };

    ele.addeventlistener('click', this.onclicka, false);
    ele.addeventlistener('click', this.onclickb.bind(this), false);
};

new foo(document.body);

2. 通过定制的函数handleevent去捕获任意类型

var bar = function (ele) {
    this.ele = ele;
    this.name = 'this is bar';
    this.handleevent = function (e) {
        console.log(this.name);
        switch (e.type) {
            case 'click':
                console.log('trigger click...');
                break;
            case 'dblclick':
                console.log('trigger dblclick...');
                break;
        }
    };

    ele.addeventlistener('click', this, false);
    ele.addeventlistener('dblclick', this, false);
};
bar.prototype.remove = function () {
    // 你也可以移除这些监听事件
    this.ele.removeeventlistener('click', this, false);
    this.ele.removeeventlistener('dblclick', this, false);
};

var bar = new bar(document.body);
bar.remove();

3. 给eventlistener传递一个函数,调用想要访问对应作用域对象的方法

但是这样做绑定的事件成为了匿名函数,是不能取消绑定的。

class someclass {
    constructor() {
        this.name = 'this is a class';
    }
    
    register() {
        const that = this;
        window.addeventlistener('keydown', function (ev) { return that.foo(ev); });
    }
    
    foo(e) {
        console.log(this.name);
        switch (e.keycode) {
            case 65:
                console.log('a');
                break;
            case 13:
                console.log('enter');
                break;
        }
    }
}
    
const obj = new someclass();
obj.register();

《$.on()方法和addEventListener改变this指向.doc》

下载本文的Word格式文档,以方便收藏与打印。