2016-07-01 1 views
0

私はこれが最善のコードで尋ねていると思う:DOM CustomEventリスナー

var event = new CustomEvent("custom", {bubbles: true}); // Create Event 

// Create and attach element 
var element = document.createElement("div"); 
document.body.appendChild(element); 

element.addEventListener("custom", function(e) { 
    console.log("listening"); 
}); 

// At this point I thought that if the "custom" event were fired that my 
// element listing would be triggered with the listener callback. 
// But.... 

document.body.dispatchEvent(event); 
// check the console... nothing :(

// the only way I am able to get my element event listener to fire is if 
// the element calling the dispatchEvent(event) is the element itself. 
element.dispatchEvent(event); 

私が間違って何をしているのですか?これはイベントの仕組みですか? 私の質問は、イベントがリスナーコールバック

element.addEventListener("custom", function(){}); 

答えて

0

を含む要素から

dispatchEvent(event) 

を派遣していないときは、ある要素にイベントを送出する必要があり、私はカスタムイベントに耳を傾けない方法です実際にそれを聞いている、あるいはバブルになっているとチェーンの下にある要素です。あなたは

element.dispatchEvent(event); 
下向きDIVのイベントをリッスンして、BODYタグにイベントを送出し、泡にそれを期待することはできません

は、イベントを発生させる適切な方法ですが、それは勝ちました身体から子供へのバブルは、イベントはDOMチェーンを上方に泡立たせます。

+0

これに追加するには逆に、リスナーをドキュメント本体に適用すると、そのイベントが本体または要素でトリガされるかどうかが発生します。 – relic

+0

@relic - もちろん、イベントリスナーがボディー上にあった場合、ボディーまたはその子のイベントをトリガーすると、イベントハンドラーが起動します。 – adeneo

+0

私はあなたや何かを修正するためにそれを持ち出していませんでしたが、OPの利益のためにそれを指摘しました。 – relic

関連する問題