JAVASCRIPT   8

event_target.js

Guest on 21st May 2021 06:44:25 AM

  1. var Event = require('./event');
  2.  
  3. var EventTarget = {
  4.   onopen:     null,
  5.   onmessage:  null,
  6.   onerror:    null,
  7.   onclose:    null,
  8.  
  9.   addEventListener: function(eventType, listener, useCapture) {
  10.     this._listeners = this._listeners || {};
  11.     var list = this._listeners[eventType] = this._listeners[eventType] || [];
  12.     list.push(listener);
  13.   },
  14.  
  15.   removeEventListener: function(eventType, listener, useCapture) {
  16.     if (!this._listeners || !this._listeners[eventType]) return;
  17.  
  18.     if (!listener) {
  19.       delete this._listeners[eventType];
  20.       return;
  21.     }
  22.     var list = this._listeners[eventType],
  23.         i    = list.length;
  24.  
  25.     while (i--) {
  26.       if (listener !== list[i]) continue;
  27.       list.splice(i,1);
  28.     }
  29.   },
  30.  
  31.   dispatchEvent: function(event) {
  32.     event.target = event.currentTarget = this;
  33.     event.eventPhase = Event.AT_TARGET;
  34.  
  35.     if (this['on' + event.type])
  36.       this['on' + event.type](event);
  37.  
  38.     if (!this._listeners || !this._listeners[event.type]) return;
  39.  
  40.     this._listeners[event.type].forEach(function(listener) {
  41.       listener(event);
  42.     }, this);
  43.   }
  44. };
  45.  
  46. module.exports = EventTarget;

Raw Paste


Login or Register to edit or fork this paste. It's free.