简体   繁体   中英

Event Delegation in Polymer

Is there any way to add event delegation from outer body elements into shadow elements?

For instance, I want a special function to fire whenever someone clicks an anchor with class="special" .

Normally (in jquery):

$('body').on('click', 'a.special', myFunction);

However, this doesn't seem possible using the shadow DOM, at least with everything I've tried. Do I really need to add these handlers to every instance of a.special as they appear in some template?

In your example, you can still use event delegation with custom elements:

$('body').on('click', 'my-element', myFunction);

The difference is that the event will look like it came from my-element instead of an a.special inside of your element's shadow dom. That's because the event model does retargeting to hide the implementation details of your shadow dom.

You can also setup listeners inside your element that fire an event when a.special is clicked: http://www.polymer-project.org/articles/communication.html#utilizing-event-delegation

For something more sophisticated, check out the Communication & Message Passing on the Polymer site. Particularly, <core-signals> can be used for a pubsub-like pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM