将事件从一个dom节点路由到另一个dom节点而不使用JQUERY

时间:2011-09-28 21:58:38

标签: javascript webos

我的问题完全像:How do I pass javascript events from one element to another?,除了我需要一个原始的JS解决方案。

我有一个网络应用程序,其UI具有一系列元素,可以在页面上相互滚动。基本上我有iframe(不完全,但原则上),以及一个浮动头,它位于它上面的z层。当我滚动iframe中的元素时,它也会向上移动浮动标题。

但是,我还需要在拖动标题时滚动基础文档。

这是一个触摸屏界面,所以我正在尝试onmousemove和ontouchmove事件。

我有以下代码,但它似乎没有做任何事情:

setupScrollFromHeader: function setupScrollFromHeader() {
            // webos enyo stuff. Don't worry about it. just know that I get the
            // raw dom elements through the this.$.elem.node syntax
        var body = this.$.body, header = this.$.mailHeaderUnit;
        if (!header.hasNode() && !body.hasNode()) {
            return;
        }
        body = body.node;
            // end enyo specific stuff

        header.node.addEventListener('touchmove', function(event) {
            console.log("### touch move");
            event.preventDefault();
            body.dispatchEvent(event);
            var touch = event.touches[0];
                console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
            }, true);
        console.log("### set this stuff up");
    }

我正在使用dispatchEvent来转发事件,每个: https://developer.mozilla.org/en/DOM/element.dispatchEvent

我已经尝试过touchmove和mousemove事件本身,切换防止默认,以及使用true / false标志更改冒泡行为。

在所有情况下,我都看到日志打印出来,但事件永远不会传递给底层元素。我究竟做错了什么?是否有可能以这种方式传递事件?

1 个答案:

答案 0 :(得分:2)

所以这是路由事件的正确方法。看起来我正在谈论的小部件在接收touchmove事件之前需要一个mousedown事件。为了获得最大的兼容性,我添加了鼠标和触摸的监听器,以便在浏览器和设备上进行测试。

我想出了以下内容:

setupScrollFromHeader: function setupScrollFromHeader() {
        if (setupScrollFromHeader.complete) {
            return;
        }
        var body = this.$.body, header = this.$.mailHeaderUnit;
        if (!header.hasNode() && !body.hasNode()) {
            return;
        }

        var header = header.node;
        var forwarder = function forwarder(event) {
                body.$.view.node.dispatchEvent(event);
            };

        ['mousedown', 'mousemove', 'touchstart', 'touchmove', 'touchend'].forEach(function(key) {
            header.addEventListener(key, forwarder, true);          
        });

        setupScrollFromHeader.complete = true;
    },

在一般的浏览器案例中,您可以使用两个按钮测试此类转发,通过dispatchEvent(...)将click事件从一个按钮路由到另一个按预期工作。

即:

var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');

button1.addEventListener('click', function(event) {
            button2.dispatchEvent(event);
}, true);

button2.addEventListener('click', function(event) {
    alert("Magnets. How do they work?");
}, true);

单击button1将触发button2的处理程序。

相关问题