kontra icon indicating copy to clipboard operation
kontra copied to clipboard

Non-window based asset loader

Open UnbrandedTech opened this issue 2 years ago • 1 comments

What's your take on a singleton asset loader?

class AssetLoader {
    constuctor() {
        this.image_path = ''
        this.audio_path = ''
        this.data_path = ''

        this.images = {}
        this.audio = {}
        this.data = {}
    }

    setAudioPath(path) {
        this.audio_path = path
    }

    async addAudio(url) {
        const result = fetch(url)
        this.audio[resolved] = result
        this.audio[path] = result
        this.audio[name] = result
    }

    getAudio(id) {
        return this.audio[id]
    }
}

const singleton = new AssetLoader()

export default singleton

We could expose it to the window with window.__k = singleton and then in we could use it to fetch assets without reaching for the window import { AssetLoader } from 'kontrajs'; await AssetLoader.addAudio(url); const image = AssetLoader.getImage(url)

UnbrandedTech avatar Feb 18 '22 00:02 UnbrandedTech

Interesting idea. Is there a particular use-case or reason a singleton would be more helpful over individual functions? One of the main reasons they are separate functions is to enable tree-shaking out the parts of asset loading you are not using (like all the audio loading code if you're only loading images).

straker avatar Feb 18 '22 03:02 straker