import { isPlainObject, extend, each, isArray } from "./2.base"; import { Models } from "./5.inject"; export function useInWorker () { function createWatcher (model, keyOrFn, cb, options) { if (isPlainObject(cb)) { options = cb; cb = cb.handler; } options = options || {}; return Fix.watch(model, keyOrFn, cb, extend(options, { store: model, })); } const models = {}, watches = {}; addEventListener("message", e => { const data = e.data; let store; switch (data.eventType) { case "action": models[data.name][data.action](...data.args); break; case "destroy": each(watches[data.name], (i, unwatches) => { unwatches = isArray(unwatches) ? unwatches : [unwatches]; each(unwatches, (j, unwatch) => { unwatch(); }); }); delete models[data.name]; delete watches[data.name]; break; case "create": store = models[data.name] = Models.getModel(data.type, data.options); watches[data.name] = []; each(data.watches, (i, key) => { watches[data.name].push(createWatcher(store.model, key, (newValue, oldValue) => { postMessage(extend({}, data, { eventType: "watch", currentWatchType: key, }, { args: [newValue, oldValue] })); })); }); postMessage(extend({}, data, { eventType: "create", }, { msg: store.model })); break; default: break; } }, false); }