JSFiddle - React, Tailwind, and code Playground
by joplomacedo
JavaScript
class Store {
constructor(obj, isRoot = true, rootStore = null) {
this.init = obj.init;
this.actions = obj.actions;
this.mutations = obj.mutations;
this.getters = obj.getters;
this.state = obj.state;
this.root = rootStore || this;
this.modules = obj.modules;
this.modules.forEach(mdl => new Store(mdl, false, this.root));
}
_call (which, moduleAndMethodNamesStr, ...args) {
let modulePathAndMethodName = moduleAndMethodNamesStr.split('.');
let methodName = modulePathAndMethodName[modulePathAndMethodName.length -1];
let modulePath = modulePathAndMethodName.slice(0, -1);
let mdl = modulePath.reduce( (res, item) => {
return res ? res[item] : item;
}, null)
let ctx = mdl[which];
let method = ctx[methodName];
return method.call(ctx, {
state: mdl.state,
commit: mdl.commit,
get: mdl.get,
dispatch: mdl.dispatch,
root: this.root,
}, ...args);
}
dispatch (moduleAndActionNames, ...args) {
return this._call('actions', moduleAndActionNames, ...args);
}
commit (moduleAndMutationNames, ...args) {
return this._call('mutations', moduleAndMutationNames, ...args);
}
get (moduleAndGetterNames, ...args) {
return this._call('getters', moduleAndGetterNames, ...args);
}
};
store = new Store({
state: {
a: 3
},
mutations: {
incA( {state}, amount) {
this.a += amount;
return this.A;
}
},
actions: {
incA( {commit}, amount ) {
re commit('incA', amount)
}
}
})