OLD | NEW |
| (Empty) |
1 | |
2 (function(){ | |
3 /** | |
4 `iron-signals` provides basic publish-subscribe functionality. | |
5 | |
6 Note: avoid using `iron-signals` whenever you can use | |
7 a controller (parent element) to mediate communication | |
8 instead. | |
9 | |
10 To send a signal, fire a custom event of type `iron-signal`, with | |
11 a detail object containing `name` and `data` fields. | |
12 | |
13 this.fire('iron-signal', {name: 'hello', data: null}); | |
14 | |
15 To receive a signal, listen for `iron-signal-<name>` event on a | |
16 `iron-signals` element. | |
17 | |
18 <iron-signals on-iron-signal-hello="{{helloSignal}}"> | |
19 | |
20 You can fire a signal event from anywhere, and all | |
21 `iron-signals` elements will receive the event, regardless | |
22 of where they are in DOM. | |
23 | |
24 @demo demo/index.html | |
25 */ | |
26 Polymer({ | |
27 is: 'iron-signals', | |
28 | |
29 attached: function() { | |
30 signals.push(this); | |
31 }, | |
32 detached: function() { | |
33 var i = signals.indexOf(this); | |
34 if (i >= 0) { | |
35 signals.splice(i, 1); | |
36 } | |
37 } | |
38 }); | |
39 | |
40 // private shared database | |
41 var signals = []; | |
42 | |
43 // signal dispatcher | |
44 function notify(name, data) { | |
45 // convert generic-signal event to named-signal event | |
46 var signal = new CustomEvent('iron-signal-' + name, { | |
47 // if signals bubble, it's easy to get confusing duplicates | |
48 // (1) listen on a container on behalf of local child | |
49 // (2) some deep child ignores the event and it bubbles | |
50 // up to said container | |
51 // (3) local child event bubbles up to container | |
52 // also, for performance, we avoid signals flying up the | |
53 // tree from all over the place | |
54 bubbles: false, | |
55 detail: data | |
56 }); | |
57 // dispatch named-signal to all 'signals' instances, | |
58 // only interested listeners will react | |
59 signals.forEach(function(s) { | |
60 s.dispatchEvent(signal); | |
61 }); | |
62 } | |
63 | |
64 // signal listener at document | |
65 document.addEventListener('iron-signal', function(e) { | |
66 notify(e.detail.name, e.detail.data); | |
67 }); | |
68 | |
69 })(); | |
OLD | NEW |