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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM