UNPKG

meta-next

Version:

91 lines (75 loc) 1.63 kB
class Resources { constructor() { this.resources = {} this.watchers = {} this.loading = false this.numToLoad = 0 } load(config) { const classes = this.Resource.__inherit for(let key in config) { if(this.resources[key]) { console.warn(`(Resources.load) There is already resource with id: ${key}`) continue } const itemConfig = config[key] const cls = classes[itemConfig.type] if(!cls) { console.warn(`(Resources.load) No such resoruce type registered: ${itemConfig.type}`) continue } const resource = new cls(itemConfig) this.resources[key] = resource } } resourceLoading(resource) { if(this.numToLoad === 0) { this.loading = true this.emit("loading") } this.numToLoad++ } resourceLoaded(resource) { this.numToLoad-- if(this.numToLoad === 0) { this.loading = false this.emit("ready") } } get(id) { const resource = this.resources[id] return resource || null } on(event, func) { const buffer = this.watchers[event] if(buffer) { buffer.push(func) } else { this.watchers[event] = [ func ] } } off(event, func) { const buffer = this.watchers[event] if(!buffer) { return } const index = buffer.indexOf(func) if(index === -1) { return } buffer[index] = buffer[buffer.length - 1] buffer.pop() } emit(event) { const buffer = this.watchers[event] if(!buffer) { return } for(let n = 0; n < buffer.length; n++) { buffer[n]() } } } const instance = new Resources() export default instance