2017-06-01 113 views
-1

我不得不使用大型UI框架來構建Web應用程序。該框架只是簡單地將「單擊」偵聽器添加到UI元素,但我還需要一些像「touchstart」這樣的移動事件偵聽器。重寫addEventListener以與普通'click'偵聽器同時添加'touchstart'偵聽器

我的方法:

(function() { 
    Element.prototype._addEventListener = Element.prototype.addEventListener; 
    Element.prototype.addEventListener = function(a, b, c) { 
     this._addEventListener(a, b, c); 

     if (a == "click") { 
      this._addEventListener("touchstart", b, c); 
     } 
    }; 
})(); 

第二_addEventListener似乎並不管用。任何人都有建議?

更新 正如neojg提到的,它是不可能直接在的addEventListener功能的覆蓋做到這一點。我得出這樣的解決方案:如果

var list = []; 

(function() { 
    Element.prototype._addEventListener = Element.prototype.addEventListener; 
    Element.prototype.addEventListener = function(a, b, c) { 
     this._addEventListener(a, b, c); 

     if (a == "click") { 
      list.push(this); 
     } 

    }; 
})(); 

// build UI with framework 
// ... 

for (var i = 0; i < list.length; i++) { 
    var obj = list[i]; 
    obj.addEventListener("touchstart", obj.onclick); 
} 

回答

1

恕我直言事件偵聽器是用來處理「touchstart」這將混淆,以獲得「點擊」事件的事件對象 - 每有一個非常不同的事件對象。 「touchstart」「touchmove」「touchend」的順序在「點擊」時不會發生。考慮重新設計你的代碼,或者用一些「超載」的點擊來模仿這些動作,這些點擊將用適當的事件對象觸發「touchstart」,「touchmove」,「touchend」,並使用超時模擬序列。