Context.js 1.8 KB

123456789101112131415
  1. export default class Context{constructor(){this._flavors=new Map();this._eventDispatchers=new Map();}
  2. setFlavor(flavorType,flavorValue){const value=this._flavors.get(flavorType)||null;if(value===flavorValue){return;}
  3. if(flavorValue){this._flavors.set(flavorType,flavorValue);}else{this._flavors.remove(flavorType);}
  4. this._dispatchFlavorChange(flavorType,flavorValue);}
  5. _dispatchFlavorChange(flavorType,flavorValue){for(const extension of self.runtime.extensions(UI.ContextFlavorListener)){if(extension.hasContextType(flavorType)){extension.instance().then(instance=>(instance).flavorChanged(flavorValue));}}
  6. const dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher){return;}
  7. dispatcher.dispatchEventToListeners(Events.FlavorChanged,flavorValue);}
  8. addFlavorChangeListener(flavorType,listener,thisObject){let dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher){dispatcher=new Common.Object();this._eventDispatchers.set(flavorType,dispatcher);}
  9. dispatcher.addEventListener(Events.FlavorChanged,listener,thisObject);}
  10. removeFlavorChangeListener(flavorType,listener,thisObject){const dispatcher=this._eventDispatchers.get(flavorType);if(!dispatcher){return;}
  11. dispatcher.removeEventListener(Events.FlavorChanged,listener,thisObject);if(!dispatcher.hasEventListeners(Events.FlavorChanged)){this._eventDispatchers.remove(flavorType);}}
  12. flavor(flavorType){return this._flavors.get(flavorType)||null;}
  13. flavors(){return new Set(this._flavors.keys());}
  14. applicableExtensions(extensions){const targetExtensionSet=new Set();const availableFlavors=this.flavors();extensions.forEach(function(extension){if(self.runtime.isExtensionApplicableToContextTypes(extension,availableFlavors)){targetExtensionSet.add(extension);}});return targetExtensionSet;}}
  15. const Events={FlavorChanged:Symbol('FlavorChanged')};self.UI=self.UI||{};UI=UI||{};UI.Context=Context;UI.context=new Context();