簡體   English   中英

如何覆蓋原型中的事件偵聽器?

[英]How to overwrite event listener within prototype?

我正在嘗試實現兩種方法:啟動和停止。 問題是,停止似乎不起作用。

const MyObj = function(x) {
    this.x = x;
};
MyObj.prototype.start = function(el) {
    el.onclick = (function() {
        console.log(this.x);
    }).bind(this);
};
MyObj.prototype.stop = function(el) {
    el.onclick = null;
};

const obj = new MyObj("x");
document.getElementById("checkbox").onchange = function() {
    if (this.value) {
        obj.start(document.body);
    }
    else {
        obj.stop(document.body);
    }
};

我嘗試使用""function(){}代替null ,但是它們也不起作用。 如果我在瀏覽器控制台中設置onclick事件,則在調用start ,它將起作用。

我該如何解決?

obj.stop(document.body)永遠不會運行,因為this.value始終為true 您正在尋找的是this.checked

固定代碼:

const MyObj = function(x) {
    this.x = x;
};
MyObj.prototype.start = function(el) {
    el.onclick = (function() {
        console.log(this.x);
    }).bind(this);
};
MyObj.prototype.stop = function(el) {
    el.onclick = null;
};

const obj = new MyObj("x");
document.getElementById("checkbox").onchange = function() {
    if (this.checked) {
        obj.start(document.body);
    } else {
        obj.stop(document.body);
    }
};

另請參閱此小提琴以獲取演示。

使用addEventListenerremoveEventListener

el.addEventListener("click", someHandler);
// later...
el.removeEventListener('click', someHandler);

請注意, someHandler必須使someHandler是同一對象。 不要使用內聯函數。



我已經制作了自己的事件處理程序版本:

var EventHandler = function(){}
EventHandler.prototype.events = [];
EventHandler.prototype.functions = [];
EventHandler.prototype.addEventListener = function(e,f,obj)   // start
{
    if (obj === undefined) obj = window;
    this.events.push(e);
    this.functions.push(f);
    obj.addEventListener(e,f);
};
EventHandler.prototype.removeEventListener = function(e,obj)   // stop
{
    if (obj === undefined) obj = window;
    var i = this.events.indexOf(event);
    if (i === -1)
    {
        return;
    }
    obj.removeEventListener(event,this.functions[i]);
    this.events.splice(i,1);
    this.functions.splice(i,1);
    //this.removeEventListener(e,obj);      // to remove multiple events of the same type
}

您遇到的問題是,只有在運行start方法時,它才實際添加onclick偵聽器。

const MyObj = function(x) {
    this.x = x;
};
MyObj.prototype.start = function(el)
{
    var self = this;
    el.addEventListener("click",function()
    {
        console.log(self.x);
    });
    console.log("started");
    console.log(el);
};
MyObj.prototype.stop = function(el) {
    var self = this;
    el.removeEventListener("click",function()
    {
        console.log(self.x);
    });
    console.log("stopped");
};

var test = new MyObj(54);
test.start(document.getElementById("thing"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM