yax
Version:
Yet another store using redux. (Inspired by vuex and dva)
85 lines (65 loc) • 2.26 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _module = _interopRequireDefault(require("./module"));
var _util = require("../util");
var ModuleCollection =
/*#__PURE__*/
function () {
function ModuleCollection(rawRootModule) {
var _this = this;
// register root module
this.root = new _module["default"](rawRootModule); // register all nested modules
if (rawRootModule.modules) {
(0, _util.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 (0, _util.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["default"](rawModule);
parent.addChild(path[path.length - 1], newModule); // register nested modules
if (rawModule.modules) {
(0, _util.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;
}();
exports["default"] = ModuleCollection;