event_target.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * vim: ts=4:sw=4:expandtab
  3. *
  4. * Implements EventTarget
  5. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
  6. *
  7. */
  8. ;(function () {
  9. 'use strict';
  10. window.textsecure = window.textsecure || {};
  11. function EventTarget() {
  12. }
  13. EventTarget.prototype = {
  14. constructor: EventTarget,
  15. dispatchEvent: function(ev) {
  16. if (!(ev instanceof Event)) {
  17. throw new Error('Expects an event');
  18. }
  19. if (this.listeners === null || typeof this.listeners !== 'object') {
  20. this.listeners = {};
  21. }
  22. var listeners = this.listeners[ev.type];
  23. if (typeof listeners === 'object') {
  24. for (var i=0; i < listeners.length; ++i) {
  25. if (typeof listeners[i] === 'function') {
  26. listeners[i].call(null, ev);
  27. }
  28. }
  29. }
  30. },
  31. addEventListener: function(eventName, callback) {
  32. if (typeof eventName !== 'string') {
  33. throw new Error('First argument expects a string');
  34. }
  35. if (typeof callback !== 'function') {
  36. throw new Error('Second argument expects a function');
  37. }
  38. if (this.listeners === null || typeof this.listeners !== 'object') {
  39. this.listeners = {};
  40. }
  41. var listeners = this.listeners[eventName];
  42. if (typeof listeners !== 'object') {
  43. listeners = [];
  44. }
  45. listeners.push(callback);
  46. this.listeners[eventName] = listeners;
  47. },
  48. removeEventListener: function(eventName, callback) {
  49. if (typeof eventName !== 'string') {
  50. throw new Error('First argument expects a string');
  51. }
  52. if (typeof callback !== 'function') {
  53. throw new Error('Second argument expects a function');
  54. }
  55. if (this.listeners === null || typeof this.listeners !== 'object') {
  56. this.listeners = {};
  57. }
  58. var listeners = this.listeners[eventName];
  59. if (typeof listeners === 'object') {
  60. for (var i=0; i < listeners.length; ++ i) {
  61. if (listeners[i] === callback) {
  62. listeners.splice(i, 1);
  63. return;
  64. }
  65. }
  66. }
  67. this.listeners[eventName] = listeners;
  68. },
  69. extend: function(obj) {
  70. for (var prop in obj) {
  71. this[prop] = obj[prop];
  72. }
  73. return this;
  74. }
  75. };
  76. textsecure.EventTarget = EventTarget;
  77. }());