vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.6 KiB

  1. /**
  2. * An event bus can be used to emit events, and to subscribe to events
  3. * @constructor EventBus
  4. */
  5. function EventBus() {
  6. this.subscriptions = [];
  7. }
  8. /**
  9. * Subscribe to an event
  10. * @param {String | RegExp} event The event can be a regular expression, or
  11. * a string with wildcards, like 'server.*'.
  12. * @param {function} callback. Callback are called with three parameters:
  13. * {String} event, {*} [data], {*} [source]
  14. * @param {*} [target]
  15. * @returns {String} id A subscription id
  16. */
  17. EventBus.prototype.on = function (event, callback, target) {
  18. var regexp = (event instanceof RegExp) ?
  19. event :
  20. new RegExp(event.replace('*', '\\w+'));
  21. var subscription = {
  22. id: util.randomUUID(),
  23. event: event,
  24. regexp: regexp,
  25. callback: (typeof callback === 'function') ? callback : null,
  26. target: target
  27. };
  28. this.subscriptions.push(subscription);
  29. return subscription.id;
  30. };
  31. /**
  32. * Unsubscribe from an event
  33. * @param {String | Object} filter Filter for subscriptions to be removed
  34. * Filter can be a string containing a
  35. * subscription id, or an object containing
  36. * one or more of the fields id, event,
  37. * callback, and target.
  38. */
  39. EventBus.prototype.off = function (filter) {
  40. var i = 0;
  41. while (i < this.subscriptions.length) {
  42. var subscription = this.subscriptions[i];
  43. var match = true;
  44. if (filter instanceof Object) {
  45. // filter is an object. All fields must match
  46. for (var prop in filter) {
  47. if (filter.hasOwnProperty(prop)) {
  48. if (filter[prop] !== subscription[prop]) {
  49. match = false;
  50. }
  51. }
  52. }
  53. }
  54. else {
  55. // filter is a string, filter on id
  56. match = (subscription.id == filter);
  57. }
  58. if (match) {
  59. this.subscriptions.splice(i, 1);
  60. }
  61. else {
  62. i++;
  63. }
  64. }
  65. };
  66. /**
  67. * Emit an event
  68. * @param {String} event
  69. * @param {*} [data]
  70. * @param {*} [source]
  71. */
  72. EventBus.prototype.emit = function (event, data, source) {
  73. for (var i =0; i < this.subscriptions.length; i++) {
  74. var subscription = this.subscriptions[i];
  75. if (subscription.regexp.test(event)) {
  76. if (subscription.callback) {
  77. subscription.callback(event, data, source);
  78. }
  79. }
  80. }
  81. };