简体   繁体   English

Polymer中的事件委托

[英]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" . 例如,我希望有人单击class="special"anchor时触发特殊功能。

Normally (in jquery): 通常(在jquery中):

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

However, this doesn't seem possible using the shadow DOM, at least with everything I've tried. 但是,至少在我尝试过的所有操作中,使用影子DOM似乎都不可能做到这一点。 Do I really need to add these handlers to every instance of a.special as they appear in some template? 我真的需要将这些处理程序添加到a.special每个实例中,因为它们出现在某些模板中吗?

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. 不同之处在于该事件看起来像是来自我的元素,而不是元素的阴影dom内部的a.special That's because the event model does retargeting to hide the implementation details of your shadow dom. 这是因为事件模型确实重新定位以隐藏影子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 您还可以在元素内设置单击a.speciala.special事件的a.special器: 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. 有关更复杂的内容,请查看Polymer网站上的Communication&Message Passing Particularly, <core-signals> can be used for a pubsub-like pattern. 特别地, <core-signals>可以用于类似pubsub的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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