覆盖addEventListener以添加' touchstart'听众同时正常点击'倾听者

时间:2017-06-01 19:52:02

标签: javascript jquery

我被迫使用大型UI框架来构建Web应用程序。该框架只是添加了简单的" click"监听UI元素,但我还需要一些移动事件监听器,如" 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 个答案:

答案 0 :(得分:1)

恕我直言,如果一个事件监听器被写入处理&#34; touchstart&#34;它会被混淆以获得&#34;点击&#34;的事件对象。 event - 每个都有一个非常不同的事件对象。 &#34; touchstart&#34;的顺序&#34; touchmove&#34; &#34; touchend&#34;只有&#34;点击&#34;永远不会发生。考虑重新设计您的代码或模仿某些&#34;重载&#34;点击将触发&#34; touchstart&#34; &#34; touchmove&#34; &#34; touchend&#34;使用适当的事件对象并使用超时来模拟序列。