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

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

javascript - How to capture custom events dispatched on any of my parents

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...