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

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

标签(空格分隔): jQuery JavaScript


jQuery $.on()

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();

版权声明:本文为jehorn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/jehorn/p/10537240.html