UNPKG

yax

Version:

Yet another store using redux. (Inspired by vuex and dva)

77 lines (61 loc) 2.04 kB
import Module from './module'; import { composeReducers, forEachValue } from '../util'; var ModuleCollection = /*#__PURE__*/ function () { function ModuleCollection(rawRootModule) { var _this = this; // register root module this.root = new Module(rawRootModule); // register all nested modules if (rawRootModule.modules) { forEachValue(rawRootModule.modules, function (rawModule, key) { _this.register([key], rawModule); }); } } var _proto = ModuleCollection.prototype; _proto.get = function get(path) { return path.reduce(function (module, key) { return module.getChild(key); }, this.root); }; _proto.makeReducers = function makeReducers() { var unregister = function unregister(state, action) { var type = action.type, path = action.path; if (type === '@@yax/unregister') { var parent = path.slice(0, -1).reduce(function (cur, p) { return cur[p]; }, state); delete parent[path[path.length - 1]]; } return state; }; return composeReducers(unregister, this.root.makeReducers()); }; _proto.getNamespace = function getNamespace(path) { var module = this.root; return path.reduce(function (namespace, key) { module = module.getChild(key); return namespace + key + '/'; }, ''); }; _proto.register = function register(path, rawModule) { var _this2 = this; var parent = this.get(path.slice(0, -1)); var newModule = new Module(rawModule); parent.addChild(path[path.length - 1], newModule); // register nested modules if (rawModule.modules) { forEachValue(rawModule.modules, function (rawChildModule, key) { _this2.register(path.concat(key), rawChildModule); }); } }; _proto.unregister = function unregister(path) { var parent = this.get(path.slice(0, -1)); var key = path[path.length - 1]; parent.removeChild(key); }; return ModuleCollection; }(); export { ModuleCollection as default };