forked from Prhythm/prism-event-bus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprism-event-bus.html
356 lines (328 loc) · 11.6 KB
/
prism-event-bus.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<link rel="import" href="../polymer/polymer.html">
<script>
'use strict';
/**
* `<prism-event-bus>` is a [Polymer 2](http://polymer-project.org/) element provides compact event bus that simplifies communication between elements.
*
* # Usage
*
* Register element
*
* ```javascript
* // Register element with all event types
* PrismEventBus.register(this);
* // Register element with scoped types
* PrismEventBus.register(this, ['talk', 'walk']);
* ```
*
* Then post event anywhere
*
* ```html
* PrismEventBus.post(new CustomEvent('talk', {
* bubbles: false,
* composed: true,
* detail: {
* text: `Hello, World`
* }
* }));
* ```
*
* @memberof Prhythm
* @element prism-event-bus
* @customElement
* @polymer
* @demo demo/index.html Demo
*/
class PrismEventBus extends Polymer.Element {
static get is() { return 'prism-event-bus'; }
static get properties() {
return {
/**
* Name of event bus
*/
name: {
type: String,
reflectToAttribute: true
},
/**
* Registered subscribers
*/
subscribers: {
type: Array,
value: () => { return []; }
}
};
}
/**
* Dispatch event to registered subscribers
*
* @param {Event} event Event
* @param {String} name Name of bus instance
* @return {Void}
*/
static post(event, name) {
if (name) {
let bus = PrismEventBus.getInstance(name);
if (bus) {
bus.emit(event);
} else {
console.debug(`[${PrismEventBus.is}] instance '${name}' not found`);
}
} else {
Array.prototype.forEach.call(document.querySelectorAll(PrismEventBus.is), bus => {
bus.emit(event);
})
}
}
/**
* Dispatch event to registered subscribers, only allowed when event scope is sepecified
*
* @param {Event} event Event
* @param {String} name Name of bus instance
* @return {Void}
*/
static postDelayed(event, name) {
if (name) {
let bus = PrismEventBus.getInstance(name, true);
if (bus) {
bus.queue(event);
}
} else {
// Create default if not exists
PrismEventBus.getInstance('default', true);
Array.prototype.forEach.call(document.querySelectorAll(PrismEventBus.is), bus => {
bus.queue(event);
})
}
}
/**
* Register an element as subscriber
*
* @param {HTMLElement} element Subscriber
* @param {Array} types Available event types
* @param {String} name Event bus target, 'default' if not sepecified
* @return {Void}
*/
static register(element, types, name = 'default') {
if (!element || !element.dispatchEvent) return;
if (!types || types.constructor !== Array) types = [];
// Get bus instance or create if not exists
let bus = PrismEventBus.getInstance(name, true);
bus.addSubscriber(element, types);
}
/**
* Unregister a subscriber
*
* @param {HTMLElement} element
* @param {Array} types Types to be remove
* @param {String} name Event bus target, 'default' if not sepecified
* @return {Void}
*/
static unregister(element, types, name = 'default') {
if (!element || !element.dispatchEvent) return;
if (!types || types.constructor !== Array) types = [];
// Get bus instance or create if not exists
let bus = PrismEventBus.getInstance(name);
if (bus) {
bus.removeSubcriber(element, types);
}
}
/**
* Get bus instance or create if not exists
*
* @param {String} name Event bus target, 'default' if not sepecified
* @param {Boolean} init Create instance when not exists
* @return {HTMLElement} PrismEventBus instance
*/
static getInstance(name = 'default', init = false) {
let bus = document.querySelector(`${PrismEventBus.is}[name=${name}]`);
if (!bus && init) {
bus = document.createElement(PrismEventBus.is);
bus.name = name;
document.body.appendChild(bus);
}
return bus;
}
/**
* Add subscriber or append event types
*
* @param {HTMLElement} element Subscriber
* @param {Array} types Available event type
* @return {Void}
*/
addSubscriber(element, types) {
if (!element || !element.dispatchEvent) return;
if (!types || types.constructor !== Array) types = [];
// Find registered subscriber
let subscriber = this.subscribers.find(item => item.target === element);
if (subscriber) {
let union = this._union(subscriber.types, types);
if (union.length > subscriber.types.length) {
// Append new event type if types is added
subscriber.types = union;
console.debug(`[${PrismEventBus.is}] event ${types} of ${element.tagName} is registered`);
// poll event queue for new event types
this._poll(element, types)
}
} else {
// No registered subscriber found, register new one
this.set('subscribers', [{ target: element, types: types }].concat(this.subscribers));
console.debug(`[${PrismEventBus.is}] event ${types} of ${element.tagName} is registered`);
// poll event queue for new subscriber
this._poll(element, types);
}
}
/**
* Remove subscriber or remove event types
*
* @param {HTMLElement} element Subscriber
* @param {Array} types Types to be remove
* @return {Void}
*/
removeSubcriber(element, types) {
if (!element || !element.dispatchEvent) return;
if (!types || types.constructor !== Array) types = [];
// Find registered subscriber
let subscriber = this.subscribers.find(item => item.target === element);
if (subscriber) {
if (types.length === 0) {
// Remove subscriber when types is empty
this.set('subscribers', Array.from(this.subscribers.filter(item => {
return item.target !== element;
})));
console.debug(`[${PrismEventBus.is}] ${element.tagName} is unregistered`)
// Remove instance if no subscribers
if (this.subscribers.length === 0) {
this.parentElement.removeChild(this);
console.debug(`[${PrismEventBus.is}] instance '${this.name}' is destroyed`)
}
} else {
// Remove event types
let difference = this._difference(subscriber.types, types);
if (subscriber.types.length > 0 && difference.length === 0) {
// No active event type, also remove subscriber
this.removeSubcriber(element);
} else {
// Unregister types
subscriber.types = difference;
console.debug(`[${PrismEventBus.is}] event ${types} of ${element.tagName} is unregistered`)
}
}
}
}
/**
* Merge as set
*
* @param {Array} sources
* @param {Array} targets
* @return {Array}
*/
_union(sources = [], targets = []) {
let temp = {};
sources.forEach(item => {
temp[item] = true;
});
targets.forEach(item => {
temp[item] = true;
});
return Object.keys(temp);
}
/**
* Difference values
*
* @param {Array} sources
* @param {Array} targets
* @return {Array}
*/
_difference(sources = [], targets = []) {
let temp = {};
sources.forEach(item => {
temp[item] = true;
});
targets.forEach(item => {
if (item in temp) {
delete temp[item];
}
});
return Object.keys(temp);
}
/**
* Dequeue events and dispatch if type is matched
*
* @param {HTMLElement} element Subscriber
* @param {Array} types Types
* @return {Void}
*/
_poll(element, types) {
types.forEach(type => {
let queuedEvents = this._dequeue(type);
queuedEvents.forEach(event => {
console.debug(`[${PrismEventBus.is}] dispatch '${event.type}' event via ${element.tagName}`);
element.dispatchEvent(event);
});
});
}
/**
* Enueue event if no subscriber is matched
*
* @param {Event} event Post event
* @return {Void}
*/
queue(event) {
// Emit firstly
if (this.emit(event, true) === 0) {
// Enqueue if no dispatched
this._enqueue(event);
}
}
/**
* Enqueue new event
*
* @param {Event} event Post event
* @return {Void}
*/
_enqueue(event) {
let buffer = this.buffer || {};
let items = buffer[event.type] || []
items.push(event);
buffer[event.type] = items;
this.buffer = buffer;
}
/**
* Dequeue events of type
*
* @param {String} type Event type
* @return {Array} Events
*/
_dequeue(type) {
let buffer = this.buffer || {}
if (type in buffer) {
let items = buffer[type] || [];
delete buffer[type];
return items;
}
return [];
}
/**
* Dispatch event to registered subscribers
*
* @param {Event} event Event
* @param {Boolean} restricted Allows only if types is defined
* @return {Number} Dispatched counts
*/
emit(event, restricted = false) {
let count = 0;
this.subscribers.forEach(item => {
let types = item.types;
// Restricted only event type is defined
if ((!restricted && (!types || types.length === 0)) || types.indexOf(event.type) > -1) {
console.debug(`[${PrismEventBus.is}] dispatch '${event.type}' event via ${item.target.tagName}`);
item.target.dispatchEvent(event);
count++;
}
});
return count;
}
}
customElements.define(PrismEventBus.is, PrismEventBus);
</script>