diff --git a/example/src/index.js b/example/src/index.js index 4b9b756..c986709 100644 --- a/example/src/index.js +++ b/example/src/index.js @@ -2,6 +2,7 @@ import Vue from 'vue/dist/vue.esm'; import LoadImageTask from '../../src/lib/task/LoadImageTask'; +import LoadJsonTask from '../../src/lib/task/LoadJsonTask'; import LoadScriptTask from '../../src/lib/task/LoadScriptTask'; import LoadVideoTask from '../../src/lib/task/LoadVideoTask'; import TaskLoader from '../../src/lib/TaskLoader'; @@ -33,6 +34,14 @@ new Vue({ assets: ['./static/dummy-video.mp4'], }, }, + { + constructor: LoadJsonTask, + label: 'LoadJsonTask', + progress: 0, + options: { + assets: ['./static/dummy-jsonx.json'], + }, + }, { constructor: LoadScriptTask, label: 'LoadScriptTask', diff --git a/src/lib/task/LoadJsonTask.ts b/src/lib/task/LoadJsonTask.ts new file mode 100644 index 0000000..759be9c --- /dev/null +++ b/src/lib/task/LoadJsonTask.ts @@ -0,0 +1,38 @@ +import AbstractLoadTask from '../task/AbstractLoadTask'; + +/** + * @description Load external json files in the TaskLoader + * + * Example: + * ```typescript + * new LoadJsonTask({ + * assets: ['path/to/file.json'], + * onAssetLoaded: result => console.log(result), + * }) + * ``` + */ +export default class LoadJsonTask extends AbstractLoadTask { + /** + * @private + * @method loadAsset + * @param {string} src + * @param {function} update + * @returns {Promise} + */ + public loadAsset(src: string, update?: (progress: number) => void): Promise { + return new Promise((resolve: (json: any) => void, reject: (reason: string) => void) => { + fetch(src) + .then(result => { + if (!result.ok) { + throw new Error(); + } + + if (update) update(1); // TODO: implement loading progress? + + return result.json(); + }) + .then(json => resolve(json)) + .catch(reason => reject(reason)); + }); + } +}