| 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482 |
1×
1×
1×
959×
959×
1×
28990×
28990×
16947×
16947×
16947×
28990×
28990×
28990×
6276×
6276×
28990×
28990×
28990×
38361×
1×
606×
606×
602×
602×
602×
606×
373×
373×
606×
606×
1×
884×
884×
884×
885×
1×
24559×
24559×
24559×
1×
41910×
41910×
14×
14×
41910×
41910×
41910×
25604×
16306×
3380×
12926×
16306×
16306×
16306×
16306×
16306×
16306×
16306×
16306×
16304×
2×
16304×
1×
3×
1×
918×
1×
16306×
27210×
16×
27194×
16304×
1×
27194×
27194×
27191×
4130×
4130×
27191×
82×
3×
2×
2×
2×
27192×
1×
38361×
38361×
16262×
4511×
4511×
33850×
1×
39246×
39246×
25987×
39246×
1×
885×
885×
884×
1130×
1130×
463×
1×
1×
4705×
1×
87×
1×
24560×
27194×
| import {
isFunction,
isArray,
isNumber,
bind,
assign
} from 'min-dash';
var FN_REF = '__fn';
var DEFAULT_PRIORITY = 1000;
var slice = Array.prototype.slice;
/**
* A general purpose event bus.
*
* This component is used to communicate across a diagram instance.
* Other parts of a diagram can use it to listen to and broadcast events.
*
*
* ## Registering for Events
*
* The event bus provides the {@link EventBus#on} and {@link EventBus#once}
* methods to register for events. {@link EventBus#off} can be used to
* remove event registrations. Listeners receive an instance of {@link Event}
* as the first argument. It allows them to hook into the event execution.
*
* ```javascript
*
* // listen for event
* eventBus.on('foo', function(event) {
*
* // access event type
* event.type; // 'foo'
*
* // stop propagation to other listeners
* event.stopPropagation();
*
* // prevent event default
* event.preventDefault();
* });
*
* // listen for event with custom payload
* eventBus.on('bar', function(event, payload) {
* console.log(payload);
* });
*
* // listen for event returning value
* eventBus.on('foobar', function(event) {
*
* // stop event propagation + prevent default
* return false;
*
* // stop event propagation + return custom result
* return {
* complex: 'listening result'
* };
* });
*
*
* // listen with custom priority (default=1000, higher is better)
* eventBus.on('priorityfoo', 1500, function(event) {
* console.log('invoked first!');
* });
*
*
* // listen for event and pass the context (`this`)
* eventBus.on('foobar', function(event) {
* this.foo();
* }, this);
* ```
*
*
* ## Emitting Events
*
* Events can be emitted via the event bus using {@link EventBus#fire}.
*
* ```javascript
*
* // false indicates that the default action
* // was prevented by listeners
* if (eventBus.fire('foo') === false) {
* console.log('default has been prevented!');
* };
*
*
* // custom args + return value listener
* eventBus.on('sum', function(event, a, b) {
* return a + b;
* });
*
* // you can pass custom arguments + retrieve result values.
* var sum = eventBus.fire('sum', 1, 2);
* console.log(sum); // 3
* ```
*/
export default function EventBus() {
this._listeners = {};
// cleanup on destroy on lowest priority to allow
// message passing until the bitter end
this.on('diagram.destroy', 1, this._destroy, this);
}
/**
* Register an event listener for events with the given name.
*
* The callback will be invoked with `event, ...additionalArguments`
* that have been passed to {@link EventBus#fire}.
*
* Returning false from a listener will prevent the events default action
* (if any is specified). To stop an event from being processed further in
* other listeners execute {@link Event#stopPropagation}.
*
* Returning anything but `undefined` from a listener will stop the listener propagation.
*
* @param {String|Array<String>} events
* @param {Number} [priority=1000] the priority in which this listener is called, larger is higher
* @param {Function} callback
* @param {Object} [that] Pass context (`this`) to the callback
*/
EventBus.prototype.on = function(events, priority, callback, that) {
events = isArray(events) ? events : [ events ];
if (isFunction(priority)) {
that = callback;
callback = priority;
priority = DEFAULT_PRIORITY;
}
Iif (!isNumber(priority)) {
throw new Error('priority must be a number');
}
var actualCallback = callback;
if (that) {
actualCallback = bind(callback, that);
// make sure we remember and are able to remove
// bound callbacks via {@link #off} using the original
// callback
actualCallback[FN_REF] = callback[FN_REF] || callback;
}
var self = this,
listener = { priority: priority, callback: actualCallback };
events.forEach(function(e) {
self._addListener(e, listener);
});
};
/**
* Register an event listener that is executed only once.
*
* @param {String} event the event name to register for
* @param {Function} callback the callback to execute
* @param {Object} [that] Pass context (`this`) to the callback
*/
EventBus.prototype.once = function(event, priority, callback, that) {
var self = this;
if (isFunction(priority)) {
that = callback;
callback = priority;
priority = DEFAULT_PRIORITY;
}
Iif (!isNumber(priority)) {
throw new Error('priority must be a number');
}
function wrappedCallback() {
self.off(event, wrappedCallback);
return callback.apply(that, arguments);
}
// make sure we remember and are able to remove
// bound callbacks via {@link #off} using the original
// callback
wrappedCallback[FN_REF] = callback;
this.on(event, priority, wrappedCallback);
};
/**
* Removes event listeners by event and callback.
*
* If no callback is given, all listeners for a given event name are being removed.
*
* @param {String|Array<String>} events
* @param {Function} [callback]
*/
EventBus.prototype.off = function(events, callback) {
events = isArray(events) ? events : [ events ];
var self = this;
events.forEach(function(event) {
self._removeListener(event, callback);
});
};
/**
* Create an EventBus event.
*
* @param {Object} data
*
* @return {Object} event, recognized by the eventBus
*/
EventBus.prototype.createEvent = function(data) {
var event = new InternalEvent();
event.init(data);
return event;
};
/**
* Fires a named event.
*
* @example
*
* // fire event by name
* events.fire('foo');
*
* // fire event object with nested type
* var event = { type: 'foo' };
* events.fire(event);
*
* // fire event with explicit type
* var event = { x: 10, y: 20 };
* events.fire('element.moved', event);
*
* // pass additional arguments to the event
* events.on('foo', function(event, bar) {
* alert(bar);
* });
*
* events.fire({ type: 'foo' }, 'I am bar!');
*
* @param {String} [name] the optional event name
* @param {Object} [event] the event object
* @param {...Object} additional arguments to be passed to the callback functions
*
* @return {Boolean} the events return value, if specified or false if the
* default action was prevented by listeners
*/
EventBus.prototype.fire = function(type, data) {
var event,
listeners,
returnValue,
args;
args = slice.call(arguments);
if (typeof type === 'object') {
event = type;
type = event.type;
}
Iif (!type) {
throw new Error('no event type specified');
}
listeners = this._listeners[type];
if (!listeners) {
return;
}
// we make sure we fire instances of our home made
// events here. We wrap them only once, though
if (data instanceof InternalEvent) {
// we are fine, we alread have an event
event = data;
} else {
event = this.createEvent(data);
}
// ensure we pass the event as the first parameter
args[0] = event;
// original event type (in case we delegate)
var originalType = event.type;
// update event type before delegation
Eif (type !== originalType) {
event.type = type;
}
try {
returnValue = this._invokeListeners(event, args, listeners);
} finally {
// reset event type after delegation
Eif (type !== originalType) {
event.type = originalType;
}
}
// set the return value to false if the event default
// got prevented and no other return value exists
if (returnValue === undefined && event.defaultPrevented) {
returnValue = false;
}
return returnValue;
};
EventBus.prototype.handleError = function(error) {
return this.fire('error', { error: error }) === false;
};
EventBus.prototype._destroy = function() {
this._listeners = {};
};
EventBus.prototype._invokeListeners = function(event, args, listeners) {
var idx,
listener,
returnValue;
for (idx = 0; (listener = listeners[idx]); idx++) {
// handle stopped propagation
if (event.cancelBubble) {
break;
}
returnValue = this._invokeListener(event, args, listener);
}
return returnValue;
};
EventBus.prototype._invokeListener = function(event, args, listener) {
var returnValue;
try {
// returning false prevents the default action
returnValue = invokeFunction(listener.callback, args);
// stop propagation on return value
if (returnValue !== undefined) {
event.returnValue = returnValue;
event.stopPropagation();
}
// prevent default on return false
if (returnValue === false) {
event.preventDefault();
}
} catch (e) {
if (!this.handleError(e)) {
console.error('unhandled error in event listener');
console.error(e.stack);
throw e;
}
}
return returnValue;
};
/*
* Add new listener with a certain priority to the list
* of listeners (for the given event).
*
* The semantics of listener registration / listener execution are
* first register, first serve: New listeners will always be inserted
* after existing listeners with the same priority.
*
* Example: Inserting two listeners with priority 1000 and 1300
*
* * before: [ 1500, 1500, 1000, 1000 ]
* * after: [ 1500, 1500, (new=1300), 1000, 1000, (new=1000) ]
*
* @param {String} event
* @param {Object} listener { priority, callback }
*/
EventBus.prototype._addListener = function(event, newListener) {
var listeners = this._getListeners(event),
existingListener,
idx;
// ensure we order listeners by priority from
// 0 (high) to n > 0 (low)
for (idx = 0; (existingListener = listeners[idx]); idx++) {
if (existingListener.priority < newListener.priority) {
// prepend newListener at before existingListener
listeners.splice(idx, 0, newListener);
return;
}
}
listeners.push(newListener);
};
EventBus.prototype._getListeners = function(name) {
var listeners = this._listeners[name];
if (!listeners) {
this._listeners[name] = listeners = [];
}
return listeners;
};
EventBus.prototype._removeListener = function(event, callback) {
var listeners = this._getListeners(event),
listener,
listenerCallback,
idx;
if (callback) {
// move through listeners from back to front
// and remove matching listeners
for (idx = listeners.length - 1; (listener = listeners[idx]); idx--) {
listenerCallback = listener.callback;
if (listenerCallback === callback || listenerCallback[FN_REF] === callback) {
listeners.splice(idx, 1);
}
}
} else {
// clear listeners
listeners.length = 0;
}
};
/**
* A event that is emitted via the event bus.
*/
function InternalEvent() { }
InternalEvent.prototype.stopPropagation = function() {
this.cancelBubble = true;
};
InternalEvent.prototype.preventDefault = function() {
this.defaultPrevented = true;
};
InternalEvent.prototype.init = function(data) {
assign(this, data || {});
};
/**
* Invoke function. Be fast...
*
* @param {Function} fn
* @param {Array<Object>} args
*
* @return {Any}
*/
function invokeFunction(fn, args) {
return fn.apply(null, args);
}
|