有没有办法拦截所有被发送的iron-signals ,而在铁信号监听器中明确指定了他们的名字?
我在我的应用程序中发出铁信号,以促进我的不同元素之间的沟通,如下:
// throughout the app
this.fire("iron-signal", {name: "do-foo"});
this.fire("iron-signal", {name: "do-bar"});
this.fire("iron-signal", {name: "do-baz"});
现在我想要另一个元素,让我们称之为analytics-tracker.html
来拦截被解雇的所有<iron-signal>
。这是一个天真的解决方案:
// in analytics-tracker.html
<iron-signals on-iron-signal-do-foo="trackEvent"></iron-signals>
<iron-signals on-iron-signal-do-bar="trackEvent"></iron-signals>
<iron-signals on-iron-signal-do-baz="trackEvent"></iron-signals>
为每个事件添加<iron-signals>
元素很快就会变得无法管理。
我可以将所有事件“捆绑”为单个命名空间事件,可以像这样跟踪:
// throughout the app
this.fire("iron-signal", {name: "general-event", data: { type: "Do Foo"}});
this.fire("iron-signal", {name: "general-event", data: { type: "Do Bar"}});
this.fire("iron-signal", {name: "general-event", data: { type: "Do Baz"}});
// in analytics-tracker.html
<iron-signals on-iron-signal-general-event="trackEvent"></iron-signals>
例如:
// throughout the app
this.fire("iron-signal", {name: "do-foo"});
this.fire("iron-signal", {name: "do-bar"});
this.fire("iron-signal", {name: "do-baz"});
// in analytics-tracker.html
<iron-signals on-iron-signal-*="trackEvent"></iron-signals>
有没有办法做类似理想解决方案的事情?
答案 0 :(得分:1)
我认为你可以为此创建一个事件监听器,这是最简单的解决方案:
// ...
ready: function()
{
// signal listener at document
document.addEventListener('iron-signal', event => {
this.trackEvent( event.detail );
});
}
// ...
铁信号正在监听文档中的全局CustomEvent,其中event.detail
具有name
和data
值,然后铁信号元素调度基于名称的事件通知方法。