UNPKG

create-dan

Version:

Dan frameworks

115 lines (101 loc) 2.75 kB
import { addInCache, removeFromCache } from '../cache' // Loader status const LoaderAssetStatus = { Waiting: 0, Progress: 1, Complete: 2, Error: 3 } /** * Loader abstract class * @param {String} header - Adress (URL, function, ...) * @param {Object} options - Options (cache, size) */ class LoaderAsset { constructor(header, { size = 1, cache = false, attributes = null, priority = 9999999 }) { this.header = header this.priority = priority this.body = null this.size = size this.status = LoaderAssetStatus.Waiting this._cache = cache this._fetch = null this.attributes = attributes this._loading = {} this.loading = new Promise((resolve, reject) => { this._loading.resolve = resolve this._loading.reject = reject }) // Cache this.cache = cache } /** * Start loading */ load() { this.status = LoaderAssetStatus.Progress // Already loaded if (this.status === LoaderAssetStatus.Complete) { this._loading.resolve(this.body) } else { // Start if (this._fetch === null) { this._fetch = this.fetch() } // Wait this._fetch.then((body) => { // Complete this.status = LoaderAssetStatus.Complete this.body = body // Attributes if(typeof body === 'object') { for(let id in this.attributes) { if(body[id] === undefined) { body[id] = this.attributes[id] } } } this._loading.resolve(body) }).catch((error) => { // Error this.status = LoaderAssetStatus.Error this.body = null this._loading.reject(error) }) } return this.loading } /** * Fetch the body asset */ fetch() { return new Promise(function (resolve, reject) { reject('fetch() is not impleted') }) } /** * Get cache status * @returns {Boolean} */ get cache() { return this._cache } /** * Set cache status * @param {Boolean} cache - Cache status */ set cache(cache) { // Add if (cache) { addInCache(this.id, this) } // Remove else { removeFromCache(this.id, this) } this._cache = cache } } export default LoaderAsset export { LoaderAsset, LoaderAssetStatus }