2011-09-28 64 views
3

我的問題完全是這樣的:How do I pass javascript events from one element to another?除了我需要一個原始的JS解決方案。從一個DOM節點到另一個節點的路由事件沒有JQUERY

我已經有了一個web應用程序,其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標誌更改冒泡行爲。

在所有情況下,我都會看到日誌打印出來,但事件永遠不會傳遞到基礎元素。我究竟做錯了什麼?這種方式甚至可以傳遞事件嗎?

+0

您顯示的代碼不完整。請顯示**整個**(相關)源代碼(例如'this。$。mailHeaderUnit','this。$','this。$。body'的定義) –

+0

這是無關緊要的。只要知道我有我需要的節點。 header.node讓我獲得浮動頭的原始dom節點。 Body.node讓我獲得底層主體的原始節點。 – Gopherkhan

+0

[如何克隆或重新分派DOM事件?](https://stackoverflow.com/questions/11974262/how-to-clone-or-re-dispatch-dom-events) –

回答

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); 

點擊按鈕1將火BUTTON2的處理程序。

相關問題