Object.js 1.6 KB

12345678910111213
  1. import{EventTarget}from'./EventTarget.js';export class ObjectWrapper{constructor(){this._listeners;}
  2. addEventListener(eventType,listener,thisObject){if(!listener){console.assert(false);}
  3. if(!this._listeners){this._listeners=new Map();}
  4. if(!this._listeners.has(eventType)){this._listeners.set(eventType,[]);}
  5. this._listeners.get(eventType).push({thisObject:thisObject,listener:listener});return{eventTarget:this,eventType:eventType,thisObject:thisObject,listener:listener};}
  6. once(eventType){return new Promise(resolve=>{const descriptor=this.addEventListener(eventType,event=>{this.removeEventListener(eventType,descriptor.listener);resolve(event.data);});});}
  7. removeEventListener(eventType,listener,thisObject){console.assert(listener);if(!this._listeners||!this._listeners.has(eventType)){return;}
  8. const listeners=this._listeners.get(eventType);for(let i=0;i<listeners.length;++i){if(listeners[i].listener===listener&&listeners[i].thisObject===thisObject){listeners[i].disposed=true;listeners.splice(i--,1);}}
  9. if(!listeners.length){this._listeners.delete(eventType);}}
  10. hasEventListeners(eventType){return!!(this._listeners&&this._listeners.has(eventType));}
  11. dispatchEventToListeners(eventType,eventData){if(!this._listeners||!this._listeners.has(eventType)){return;}
  12. const event=({data:eventData});const listeners=this._listeners.get(eventType).slice(0);for(let i=0;i<listeners.length;++i){if(!listeners[i].disposed){listeners[i].listener.call(listeners[i].thisObject,event);}}}}
  13. self.Common=self.Common||{};Common=Common||{};Common.Object=ObjectWrapper;Common.Object._listenerCallbackTuple;