Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to capture custom events that are emitted on "one of my parents". For example:

HTML

<button id="button">
 send event
</button>

<ul id="wrapper">
  <li id="inner">inner</li>
</ul>

JavaScript:

var but = document.getElementById('button')
var wrap = document.getElementById('wrapper')
var inner = document.getElementById('inner')

but.addEventListener('click', function(e) {
  console.log("clicked")
  custom = new Event("hide", { bubbles: false })
  wrap.dispatchEvent(custom)
})
wrap.addEventListener('hide', function(e){ console.log("wrapper hidden") }, true)
inner.addEventListener('hide', function(e){ console.log("inner hidden") }, true)

See this JS fiddle: https://jsfiddle.net/u7sgowce/

I need this to (also) render "inner hidden", and not just "wrapper hidden".

I need the inner.addEventListener to react to this custom event on its parent. There won't be an event listener on wrapper in the real code: the code that has this event-listener does not know about the parent wrapper at all. And the code that emits the event is not aware of what children the wrapper may contain.

If possible, allowing for arbitrary nesting is even nicer. E.g. allowing an event-listener on the <input> in the following:

<button id="button">
 send event
</button>

<ul id="wrapper">
  <li id="inner"><input type="checkbox" /></li>
</ul>

Is this possible at all? Do I simply misunderstand or use the bubbling or capturing wrong?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...