# all files / diagram-js/lib/core/ EventBus.js

91.54% Statements 119/130
82.14% Branches 46/56
95.45% Functions 21/22
91.54% Lines 119/130

    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
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512

    1×

    1×

    1×

    1371×

    1371×

    1×

    322139×

    322139×
    75826×
    75826×
    75826×

    322139×

    322139×

    322139×
    29444×

    29444×

    322139×

    322139×
    361651×

    1×
    779×

    779×
    779×
    779×
    779×

    779×

    506×

    506×

    506×

    779×

    779×

    1×

    1423×

    1423×

    1423×
    1425×

    1×
    152610×

    152610×

    152610×

    1×

    229476×

    229476×

    229476×

    229476×

    229476×
    97282×

    132194×

    21979×

    110215×

    132194×

    132194×

    132194×
    132194×

    132194×
    132194×

    132194×
    132194×

    132194×

    132194×

    1×

    1×
    1271×

    1×

    132194×

    256670×
    24788×

    231882×

    231882×

    132194×

    1×

    231882×

    231882×

    231882×
    27698×
    27698×

    231882×
    1347×

    231882×

    1×

    361651×

    361651×
    208291×

    208291×

    153360×

    273749×

    40166×

    40166×
    15771×

    24395×

    40166×

    233583×
    233583×

    113194×

    1×
    363076×

    1×
    233313×

    1×

    1425×

    1425×

    1×

    1×

    1424×

    2602×

    2602×

    2602×
    1130×
    504×

    626×

    2602×
    2602×

    1×
    28042×

    1×
    1370×

    1×
    152610×

    231882×

     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;

      events.forEach(function(e) {
        self._addListener(e, {
          priority: priority,
          callback: actualCallback,
          next: null
        });
      });
    };

    /**
     * Register an event listener that is executed only once.
     *
     * @param {String} event the event name to register for
     * @param {Number} [priority=1000] the priority in which this listener is called, larger is higher
     * @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;

      Eif (isFunction(priority)) {
        that = callback;
        callback = priority;
        priority = DEFAULT_PRIORITY;
      }

      Iif (!isNumber(priority)) {
        throw new Error('priority must be a number');
      }

      function wrappedCallback() {
        var result = callback.apply(that, arguments);

        self.off(event, wrappedCallback);

        return result;
      }

      // 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,
          firstListener,
          returnValue,
          args;

      args = slice.call(arguments);

      Iif (typeof type === 'object') {
        event = type;
        type = event.type;
      }

      Iif (!type) {
        throw new Error('no event type specified');
      }

      firstListener = this._listeners[type];

      if (!firstListener) {
        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, firstListener);
      } 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
      Iif (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, listener) {

      var returnValue;

      while (listener) {

        // handle stopped propagation
        if (event.cancelBubble) {
          break;
        }

        returnValue = this._invokeListener(event, args, listener);

        listener = listener.next;
      }

      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 listener = this._getListeners(event),
          previousListener;

      // no prior listeners
      if (!listener) {
        this._setListeners(event, newListener);

        return;
      }

      // ensure we order listeners by priority from
      // 0 (high) to n > 0 (low)
      while (listener) {

        if (listener.priority < newListener.priority) {

          newListener.next = listener;

          if (previousListener) {
            previousListener.next = newListener;
          } else {
            this._setListeners(event, newListener);
          }

          return;
        }

        previousListener = listener;
        listener = listener.next;
      }

      // add new listener to back
      previousListener.next = newListener;
    };

    EventBus.prototype._getListeners = function(name) {
      return this._listeners[name];
    };

    EventBus.prototype._setListeners = function(name, listener) {
      this._listeners[name] = listener;
    };

    EventBus.prototype._removeListener = function(event, callback) {

      var listener = this._getListeners(event),
          nextListener,
          previousListener,
          listenerCallback;

      if (!callback) {
        // clear listeners
        this._setListeners(event, null);

        return;
      }

      while (listener) {

        nextListener = listener.next;

        listenerCallback = listener.callback;

        if (listenerCallback === callback || listenerCallback[FN_REF] === callback) {
          if (previousListener) {
            previousListener.next = nextListener;
          } else {
            // new first listener
            this._setListeners(event, nextListener);
          }
        }

        previousListener = listener;
        listener = nextListener;
      }
    };

    /**
     * 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);
    }