From ebda10a71a50becab0a1d5fa3fc954db65cc73dc Mon Sep 17 00:00:00 2001 From: imtaotao Date: Wed, 20 Nov 2019 13:56:37 +0800 Subject: [PATCH] refactor: optimize useState method --- demo/pages/module/index.js | 70 +++++++++++++++++++------------------- demo/store/mpstore.esm.js | 20 ++++++----- dist/mpstore.common.js | 20 ++++++----- dist/mpstore.es6m.js | 15 ++++---- dist/mpstore.esm.js | 20 ++++++----- dist/mpstore.min.js | 2 +- package.json | 2 +- src/module.js | 5 +-- src/store.js | 13 +++---- 9 files changed, 91 insertions(+), 76 deletions(-) diff --git a/demo/pages/module/index.js b/demo/pages/module/index.js index ea9d9b2..de3db0f 100644 --- a/demo/pages/module/index.js +++ b/demo/pages/module/index.js @@ -6,40 +6,40 @@ Page({ storeConfig: { travelLimit: 5, defineReducer (store) { - // store.add('one', { + store.add('one', { + partialState: { + name: 'chen', + }, + setter: (state, payload) => ({ name: payload }) + }) + store.add('two', { + namespace: 'a', + partialState: { + age: 0, + }, + setter: (state, payload) => ({ age: payload }) + }) + store.add('three', { + namespace: 'a.b', + partialState: { + sex: 'man', + }, + setter: (state, payload) => ({ sex: payload }) + }) + + // store.add('action', { // partialState: { - // name: 'chen', - // }, - // setter: (state, payload) => ({ name: payload }) + // a: {}, + // } // }) // store.add('two', { - // namespace: 'a', - // partialState: { - // age: 0, - // }, - // setter: (state, payload) => ({ age: payload }) + // namespace: 'b', + // partialState: {}, // }) // store.add('three', { // namespace: 'a.b', - // partialState: { - // sex: 'man', - // }, - // setter: (state, payload) => ({ sex: payload }) - // }) - - store.add('action', { - partialState: { - a: {}, - } - }) - // store.add('two', { - // namespace: 'b', - // partialState: {}, + // partialState: { a: 1 }, // }) - store.add('three', { - namespace: 'a.b', - partialState: { a: 1 }, - }) // store.add('four', { // namespace: 'a.a', // partialState: { b: 2 }, @@ -114,14 +114,14 @@ Page({ // useState: () => (['taoo.tao', { // index: state => state.index, // }]), - // travelLimit: 5, - // useState () { - // return ['a.b', { - // sex: s => s.sex, - // name: (s, r) => r.name, - // age: (s, r) => r.a.age, - // }] - // }, + travelLimit: 5, + useState () { + return ['a.b', { + sex: s => s.sex, + name: (s, r) => r.name, + age: (s, r) => r.a.age, + }] + }, }, check (sex, name, age) { diff --git a/demo/store/mpstore.esm.js b/demo/store/mpstore.esm.js index 2c3e95b..f0411d0 100644 --- a/demo/store/mpstore.esm.js +++ b/demo/store/mpstore.esm.js @@ -990,17 +990,21 @@ function () { assert(isPlainObject(defineObject), '[useState] must return a plain object, ' + "but now is return a [".concat(_typeof(defineObject), "]")); - createState = function createState() { - return clone(mapObject(defineObject, function (fn) { - if (namespace === null) { + if (namespace === null) { + createState = function createState() { + return clone(mapObject(defineObject, function (fn) { return fn(store.state); - } - + })); + }; + } else { + createState = function createState() { var module = _this4.getModule(namespace, "\n\n --- from [".concat(namespace, "] of useState.")); - return fn(module, store.state); - })); - }; + return clone(mapObject(defineObject, function (fn) { + return fn(module, store.state); + })); + }; + } } if (createState !== null) { diff --git a/dist/mpstore.common.js b/dist/mpstore.common.js index c854f6c..f41b5bf 100644 --- a/dist/mpstore.common.js +++ b/dist/mpstore.common.js @@ -994,17 +994,21 @@ function () { assert(isPlainObject(defineObject), '[useState] must return a plain object, ' + "but now is return a [".concat(_typeof(defineObject), "]")); - createState = function createState() { - return clone(mapObject(defineObject, function (fn) { - if (namespace === null) { + if (namespace === null) { + createState = function createState() { + return clone(mapObject(defineObject, function (fn) { return fn(store.state); - } - + })); + }; + } else { + createState = function createState() { var module = _this4.getModule(namespace, "\n\n --- from [".concat(namespace, "] of useState.")); - return fn(module, store.state); - })); - }; + return clone(mapObject(defineObject, function (fn) { + return fn(module, store.state); + })); + }; + } } if (createState !== null) { diff --git a/dist/mpstore.es6m.js b/dist/mpstore.es6m.js index 6ec5385..d5abbb2 100644 --- a/dist/mpstore.es6m.js +++ b/dist/mpstore.es6m.js @@ -813,13 +813,14 @@ class Store { '[useState] must return a plain object, ' + `but now is return a [${typeof defineObject}]`, ); - createState = () => clone(mapObject(defineObject, fn => { - if (namespace === null) { - return fn(store.state) - } - const module = this.getModule(namespace, `\n\n --- from [${namespace}] of useState.`); - return fn(module, store.state) - })); + if (namespace === null) { + createState = () => clone(mapObject(defineObject, fn => fn(store.state))); + } else { + createState = () => { + const module = this.getModule(namespace, `\n\n --- from [${namespace}] of useState.`); + return clone(mapObject(defineObject, fn => fn(module, store.state))) + }; + } } if (createState !== null) { const useState = createState(); diff --git a/dist/mpstore.esm.js b/dist/mpstore.esm.js index 2c3e95b..f0411d0 100644 --- a/dist/mpstore.esm.js +++ b/dist/mpstore.esm.js @@ -990,17 +990,21 @@ function () { assert(isPlainObject(defineObject), '[useState] must return a plain object, ' + "but now is return a [".concat(_typeof(defineObject), "]")); - createState = function createState() { - return clone(mapObject(defineObject, function (fn) { - if (namespace === null) { + if (namespace === null) { + createState = function createState() { + return clone(mapObject(defineObject, function (fn) { return fn(store.state); - } - + })); + }; + } else { + createState = function createState() { var module = _this4.getModule(namespace, "\n\n --- from [".concat(namespace, "] of useState.")); - return fn(module, store.state); - })); - }; + return clone(mapObject(defineObject, function (fn) { + return fn(module, store.state); + })); + }; + } } if (createState !== null) { diff --git a/dist/mpstore.min.js b/dist/mpstore.min.js index df182af..b8532d4 100644 --- a/dist/mpstore.min.js +++ b/dist/mpstore.min.js @@ -1 +1 @@ -"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n-1&&e.splice(n,1)}function callHook(e,t,n){if(e&&"function"==typeof e[t])return e[t].apply(e,n)}function isEmptyObject(e){for(var t in e)return!1;return!0}function mapObject(e,t){var n={};for(var a in e)e.hasOwnProperty(a)&&(n[a]=t(e[a]));return n}function createWraper(e,t,n){return function(){for(var a,r=arguments.length,o=new Array(r),i=0;i1&&void 0!==arguments[1]?arguments[1]:new WeakMap;if(null==e||isPrimitive(e)||"function"==typeof e||e instanceof Date)return e;if(t.has(e))return t.get(e);var n="function"!=typeof e.constructor?Object.create(null):new e.constructor;for(var a in t.set(e,n),e)n[a]=clone(e[a],t);return n}function parsePath(e){var t=e.split(".");return function(e){for(var n=0,a=t.length;ne.length)for(r=t.length;--r>=e.length;){var i="".concat(n,"[").concat(r,"]");a.push(new Patch(ADD,i,t[r],e[r]))}}else a.push(new Patch(REPLACE,n,t,e))}function walkObject(e,t,n,a){for(var r in e){var o="".concat(n,".").concat(r);r in t?e[r]!==t[r]&&diffValues(e[r],t[r],o,a):a.push(new Patch(REMOVE,o,null,e[r]))}for(var i in t)if(!(i in e)){var s="".concat(n,".").concat(i);a.push(new Patch(ADD,s,t[i],null))}}function diff(e,t,n){var a=[];return walkObject(e,t,n,a),a}var REG=/[^\[\].]+(?=[\[\].])/g;function separatePath(e,t){var n=t.match(REG);if(n&&n.shift()&&n.length>0){for(var a=-1,r=null,o=e,i=null;a++0){if(!1===callHook(a,"willUpdate",[f,y,m,l])){s();continue}applyPatchs(f,m,s),"function"==typeof h&&h.call(e,f,y,m),callHook(a,"didUpdate",[f,y,l]),f.timeTravel&&f.timeTravel.push(m)}else s()}else s()}else"function"==typeof t&&t()}var TimeTravel=function(){function e(t,n,a){_classCallCheck(this,e),this.history=[],this.limit=a,this.component=t,this.GLOBALWORD=n,this.length=this.history.length,this.current=this.history.length,this.finallyState=t.data[n]}return _createClass(e,[{key:"push",value:function(e){var t=this.limit,n=this.history,a=this.GLOBALWORD,r=this.history.length,o=this.component.data;if(t>0){var i=r-t;i>=0&&this.history.splice(0,i+1),this.history.push(e),this.length=n.length,this.current=n.length,this.finallyState=clone(o[a])}}},{key:"go",value:function(e){var t=this.current,n=this.history,a=this.component,r=this.GLOBALWORD,o=this.finallyState;if(assert(r in a.data,"You can't use [timeTravel] because it only works for [global state]"),this.limit>0&&0!==e){var i=e+t,s=Math.abs(e);if(i<0||i>n.length)return void warning("Index [".concat(i,"] is not within the allowed range."),!0);for(var c=0,u=clone(a.data[r]);c++0&&applyPatchs(a,f),this.current+=e}}},{key:"forward",value:function(){this.go(1)}},{key:"back",value:function(){this.go(-1)}},{key:"toStart",value:function(){this.go(-this.current)}},{key:"toEnd",value:function(){this.go(this.history.length-this.current)}}]),e}(),COMMONACTION=function(){};function match(e,t){return e.action===COMMONACTION||t===e.action}function handleLayer(e,t,n,a,r,o){try{t.call(n,a,r,e),o()}catch(t){var i=n.hooks;o(),i&&"function"==typeof i.middlewareError?i.middlewareError(e,a,t):warning("".concat(t,"\n\n --- from middleware [").concat(e.toString(),"] action."))}}var Middleware=function(){function e(t){_classCallCheck(this,e),this.stack=[],this.store=t,this.isProcessing=!1}return _createClass(e,[{key:"use",value:function(e,t){assert(!this.isProcessing,"can't allow add new middleware in the middleware processing."),this.stack.push({fn:t,action:e})}},{key:"remove",value:function(e,t){var n=this.stack.findIndex((function(n){return n.fn===t&&n.action===e}));n>-1&&this.stack.splice(n,1)}},{key:"process",value:function(e,t,n){var a=this;this.isProcessing=!0;var r=function(){a.isProcessing=!1};if(this.stack.length>0){var o=0;!function t(i){var s=a.stack[o];for(o++;s&&!match(s,e);)s=a.stack[o++];s?handleLayer(e,s.fn,a.store,i,t,r):n(i,r)}(t)}else n(t,r)}}]),e}(),storeId=0;function assertReducer(e,t){var n=t.setter,a=t.partialState,r=e.toString();return assert("partialState"in t,"You must defined [partialState]."+"\n\n --- from [".concat(r,"] action.")),assert(isPlainObject(a),"The [partialState] must be an object."+"\n\n --- from [".concat(r,"] action.")),"function"!=typeof n&&(t.setter=function(){warning("Can't changed [".concat(r,"] action value. Have you defined a setter?")+"\n\n --- from [".concat(r,"] action."))}),t}function filterReducer(e,t,n){var a=t.toString(),r=n.namespace,o=n.partialState;if("namespace"in n)assert("string"==typeof r,"The module namespace must be a string."+"\n\n --- from [".concat(a,"] action.")),getModule(e,r)&&isEmptyObject(o)||(n.partialState=createModuleByNamespace(r,o,e,a,(function(e,t){return"The [".concat(e,"] already exists in [").concat(t,"] module, ")+"Please don't repeat defined. \n\n --- from [".concat(a,"] action.")})));else for(var i in o)assert(!e.hasOwnProperty(i),"The [".concat(i,"] already exists in global state, ")+"Please don't repeat defined. \n\n --- from [".concat(a,"] action."));return n}var Store=function(){function e(t){_classCallCheck(this,e),this.hooks=t,this.reducers=[],this.id=++storeId,this.depComponents=[],this.GLOBALWORD="global",this.isDispatching=!1,this.version="0.1.1",this.state=Object.freeze(createModule({})),this.middleware=new Middleware(this)}return _createClass(e,[{key:"add",value:function(e,t){var n=_typeof(e);assert("string"===n||"symbol"===n,"The action must be a Symbol or String, but now is [".concat(n,"].")),assert(!this.reducers.find((function(t){return t.action===e})),"Can't repeat defined [".concat(e.toString(),"] action.")),assertReducer(e,t),filterReducer(this.state,e,t),t.action=e,this.reducers.push(t);var a=t.partialState;isEmptyObject(a)||(this.state=mergeState(this.state,a))}},{key:"dispatch",value:function(e,t,n){var a=this,r=this.reducers,o=this.isDispatching,i=e.toString();assert(!o,'It is not allowed to call "dispatch" during dispatch execution.'+"\n\n --- from [".concat(i,"] action."));var s=r.find((function(t){return t.action===e}));assert(s,"The [".concat(i,"] action does not exist. ")+"Maybe you have not defined."),this.middleware.process(e,t,(function(e,t){a.isDispatching=!0;try{var r,o=s.namespace,c="string"==typeof o;if(c){var u=a.getModule(o,"\n\n --- from [".concat(i,"] action."));r=s.setter(u,e,a.state)}else r=s.setter(a.state,e);assert(isPlainObject(r),"setter function should be return a plain object."),isEmptyObject(r)||(c?(r=createModuleByNamespace(o,r,a.state,i),a.state=mergeState(a.state,r)):a.state=deepFreeze(mergeModule(a.state,r)))}finally{a.isDispatching=!1,t()}updateComponents(a,n)}))}},{key:"use",value:function(e,t){var n=this;return"function"==typeof e&&e!==COMMONACTION&&(t=e,e=COMMONACTION),this.middleware.use(e,t),function(){return n.middleware.remove(e,t)}}},{key:"setNamespace",value:function(e){assert(e&&"string"==typeof e,"The [namespace] must be a string"),this.GLOBALWORD=e}},{key:"getModule",value:function(e,t){if(assert("string"==typeof e,"the namespace mast be a string"),!e)return this.state;var n=getModule(this.state,e);return t&&null===n&&warning("The [".concat(e,"] module is not exist.").concat(t||"")),n}},{key:"addModule",value:function(e,t){var n=this;if(assert("string"==typeof e,"the namespace mast be a string"),!isEmptyObject(t)){for(var a=0,r=Object.keys(t),o=Object.getOwnPropertySymbols(t),i=function(a){var r=t[a];r.namespace=e,n.add(a,r)};a0&&applyPatchs(e,r,o)}};if(t)e.onLoad=createWraper(e.onLoad,(function(){b(this),this.store=r})),e.onUnload=createWraper(e.onUnload,null,(function(){remove(r.depComponents,this)}));else{e.lifetimes=e.lifetimes||{};var O=function(t){return e[t]||e.lifetimes[t]},w=function(t,n){return e[t]=e.lifetimes[t]=n};w("attached",createWraper(O("attached"),(function(){b(this),this.store=r}))),w("detached",createWraper(O("detached"),null,(function(){remove(r.depComponents,this)})))}}}]),e}(),version="0.1.1",nativePage=Page,nativeComponent=Component;function expandConfig(e,t,n){isEmptyObject(t)||(n?mixinMethods(e,t):(e.methods=e.methods||{},mixinMethods(e.methods,t)))}function index(e,t){var n=new Store(t),a=mixin(e);return Page=createWraper(nativePage,(function(e){callHook(t,"createBefore",[e,!0]),expandConfig(e,a,!0),n.rewirteConfigAndAddDep(e,!0)})),Component=createWraper(nativeComponent,(function(e){callHook(t,"createBefore",[e,!1]),expandConfig(e,a,!1),n.rewirteConfigAndAddDep(e,!1)})),n}exports.clone=clone,exports.createModule=createModule,exports.default=index,exports.diff=diff,exports.isModule=isModule,exports.restore=restore,exports.version=version; +"use strict";function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n-1&&e.splice(n,1)}function callHook(e,t,n){if(e&&"function"==typeof e[t])return e[t].apply(e,n)}function isEmptyObject(e){for(var t in e)return!1;return!0}function mapObject(e,t){var n={};for(var a in e)e.hasOwnProperty(a)&&(n[a]=t(e[a]));return n}function createWraper(e,t,n){return function(){for(var a,r=arguments.length,o=new Array(r),i=0;i1&&void 0!==arguments[1]?arguments[1]:new WeakMap;if(null==e||isPrimitive(e)||"function"==typeof e||e instanceof Date)return e;if(t.has(e))return t.get(e);var n="function"!=typeof e.constructor?Object.create(null):new e.constructor;for(var a in t.set(e,n),e)n[a]=clone(e[a],t);return n}function parsePath(e){var t=e.split(".");return function(e){for(var n=0,a=t.length;ne.length)for(r=t.length;--r>=e.length;){var i="".concat(n,"[").concat(r,"]");a.push(new Patch(ADD,i,t[r],e[r]))}}else a.push(new Patch(REPLACE,n,t,e))}function walkObject(e,t,n,a){for(var r in e){var o="".concat(n,".").concat(r);r in t?e[r]!==t[r]&&diffValues(e[r],t[r],o,a):a.push(new Patch(REMOVE,o,null,e[r]))}for(var i in t)if(!(i in e)){var s="".concat(n,".").concat(i);a.push(new Patch(ADD,s,t[i],null))}}function diff(e,t,n){var a=[];return walkObject(e,t,n,a),a}var REG=/[^\[\].]+(?=[\[\].])/g;function separatePath(e,t){var n=t.match(REG);if(n&&n.shift()&&n.length>0){for(var a=-1,r=null,o=e,i=null;a++0){if(!1===callHook(a,"willUpdate",[f,y,m,l])){s();continue}applyPatchs(f,m,s),"function"==typeof h&&h.call(e,f,y,m),callHook(a,"didUpdate",[f,y,l]),f.timeTravel&&f.timeTravel.push(m)}else s()}else s()}else"function"==typeof t&&t()}var TimeTravel=function(){function e(t,n,a){_classCallCheck(this,e),this.history=[],this.limit=a,this.component=t,this.GLOBALWORD=n,this.length=this.history.length,this.current=this.history.length,this.finallyState=t.data[n]}return _createClass(e,[{key:"push",value:function(e){var t=this.limit,n=this.history,a=this.GLOBALWORD,r=this.history.length,o=this.component.data;if(t>0){var i=r-t;i>=0&&this.history.splice(0,i+1),this.history.push(e),this.length=n.length,this.current=n.length,this.finallyState=clone(o[a])}}},{key:"go",value:function(e){var t=this.current,n=this.history,a=this.component,r=this.GLOBALWORD,o=this.finallyState;if(assert(r in a.data,"You can't use [timeTravel] because it only works for [global state]"),this.limit>0&&0!==e){var i=e+t,s=Math.abs(e);if(i<0||i>n.length)return void warning("Index [".concat(i,"] is not within the allowed range."),!0);for(var c=0,u=clone(a.data[r]);c++0&&applyPatchs(a,f),this.current+=e}}},{key:"forward",value:function(){this.go(1)}},{key:"back",value:function(){this.go(-1)}},{key:"toStart",value:function(){this.go(-this.current)}},{key:"toEnd",value:function(){this.go(this.history.length-this.current)}}]),e}(),COMMONACTION=function(){};function match(e,t){return e.action===COMMONACTION||t===e.action}function handleLayer(e,t,n,a,r,o){try{t.call(n,a,r,e),o()}catch(t){var i=n.hooks;o(),i&&"function"==typeof i.middlewareError?i.middlewareError(e,a,t):warning("".concat(t,"\n\n --- from middleware [").concat(e.toString(),"] action."))}}var Middleware=function(){function e(t){_classCallCheck(this,e),this.stack=[],this.store=t,this.isProcessing=!1}return _createClass(e,[{key:"use",value:function(e,t){assert(!this.isProcessing,"can't allow add new middleware in the middleware processing."),this.stack.push({fn:t,action:e})}},{key:"remove",value:function(e,t){var n=this.stack.findIndex((function(n){return n.fn===t&&n.action===e}));n>-1&&this.stack.splice(n,1)}},{key:"process",value:function(e,t,n){var a=this;this.isProcessing=!0;var r=function(){a.isProcessing=!1};if(this.stack.length>0){var o=0;!function t(i){var s=a.stack[o];for(o++;s&&!match(s,e);)s=a.stack[o++];s?handleLayer(e,s.fn,a.store,i,t,r):n(i,r)}(t)}else n(t,r)}}]),e}(),storeId=0;function assertReducer(e,t){var n=t.setter,a=t.partialState,r=e.toString();return assert("partialState"in t,"You must defined [partialState]."+"\n\n --- from [".concat(r,"] action.")),assert(isPlainObject(a),"The [partialState] must be an object."+"\n\n --- from [".concat(r,"] action.")),"function"!=typeof n&&(t.setter=function(){warning("Can't changed [".concat(r,"] action value. Have you defined a setter?")+"\n\n --- from [".concat(r,"] action."))}),t}function filterReducer(e,t,n){var a=t.toString(),r=n.namespace,o=n.partialState;if("namespace"in n)assert("string"==typeof r,"The module namespace must be a string."+"\n\n --- from [".concat(a,"] action.")),getModule(e,r)&&isEmptyObject(o)||(n.partialState=createModuleByNamespace(r,o,e,a,(function(e,t){return"The [".concat(e,"] already exists in [").concat(t,"] module, ")+"Please don't repeat defined. \n\n --- from [".concat(a,"] action.")})));else for(var i in o)assert(!e.hasOwnProperty(i),"The [".concat(i,"] already exists in global state, ")+"Please don't repeat defined. \n\n --- from [".concat(a,"] action."));return n}var Store=function(){function e(t){_classCallCheck(this,e),this.hooks=t,this.reducers=[],this.id=++storeId,this.depComponents=[],this.GLOBALWORD="global",this.isDispatching=!1,this.version="0.1.1",this.state=Object.freeze(createModule({})),this.middleware=new Middleware(this)}return _createClass(e,[{key:"add",value:function(e,t){var n=_typeof(e);assert("string"===n||"symbol"===n,"The action must be a Symbol or String, but now is [".concat(n,"].")),assert(!this.reducers.find((function(t){return t.action===e})),"Can't repeat defined [".concat(e.toString(),"] action.")),assertReducer(e,t),filterReducer(this.state,e,t),t.action=e,this.reducers.push(t);var a=t.partialState;isEmptyObject(a)||(this.state=mergeState(this.state,a))}},{key:"dispatch",value:function(e,t,n){var a=this,r=this.reducers,o=this.isDispatching,i=e.toString();assert(!o,'It is not allowed to call "dispatch" during dispatch execution.'+"\n\n --- from [".concat(i,"] action."));var s=r.find((function(t){return t.action===e}));assert(s,"The [".concat(i,"] action does not exist. ")+"Maybe you have not defined."),this.middleware.process(e,t,(function(e,t){a.isDispatching=!0;try{var r,o=s.namespace,c="string"==typeof o;if(c){var u=a.getModule(o,"\n\n --- from [".concat(i,"] action."));r=s.setter(u,e,a.state)}else r=s.setter(a.state,e);assert(isPlainObject(r),"setter function should be return a plain object."),isEmptyObject(r)||(c?(r=createModuleByNamespace(o,r,a.state,i),a.state=mergeState(a.state,r)):a.state=deepFreeze(mergeModule(a.state,r)))}finally{a.isDispatching=!1,t()}updateComponents(a,n)}))}},{key:"use",value:function(e,t){var n=this;return"function"==typeof e&&e!==COMMONACTION&&(t=e,e=COMMONACTION),this.middleware.use(e,t),function(){return n.middleware.remove(e,t)}}},{key:"setNamespace",value:function(e){assert(e&&"string"==typeof e,"The [namespace] must be a string"),this.GLOBALWORD=e}},{key:"getModule",value:function(e,t){if(assert("string"==typeof e,"the namespace mast be a string"),!e)return this.state;var n=getModule(this.state,e);return t&&null===n&&warning("The [".concat(e,"] module is not exist.").concat(t||"")),n}},{key:"addModule",value:function(e,t){var n=this;if(assert("string"==typeof e,"the namespace mast be a string"),!isEmptyObject(t)){for(var a=0,r=Object.keys(t),o=Object.getOwnPropertySymbols(t),i=function(a){var r=t[a];r.namespace=e,n.add(a,r)};a0&&applyPatchs(e,r,o)}};if(t)e.onLoad=createWraper(e.onLoad,(function(){b(this),this.store=r})),e.onUnload=createWraper(e.onUnload,null,(function(){remove(r.depComponents,this)}));else{e.lifetimes=e.lifetimes||{};var O=function(t){return e[t]||e.lifetimes[t]},w=function(t,n){return e[t]=e.lifetimes[t]=n};w("attached",createWraper(O("attached"),(function(){b(this),this.store=r}))),w("detached",createWraper(O("detached"),null,(function(){remove(r.depComponents,this)})))}}}]),e}(),version="0.1.1",nativePage=Page,nativeComponent=Component;function expandConfig(e,t,n){isEmptyObject(t)||(n?mixinMethods(e,t):(e.methods=e.methods||{},mixinMethods(e.methods,t)))}function index(e,t){var n=new Store(t),a=mixin(e);return Page=createWraper(nativePage,(function(e){callHook(t,"createBefore",[e,!0]),expandConfig(e,a,!0),n.rewirteConfigAndAddDep(e,!0)})),Component=createWraper(nativeComponent,(function(e){callHook(t,"createBefore",[e,!1]),expandConfig(e,a,!1),n.rewirteConfigAndAddDep(e,!1)})),n}exports.clone=clone,exports.createModule=createModule,exports.default=index,exports.diff=diff,exports.isModule=isModule,exports.restore=restore,exports.version=version; diff --git a/package.json b/package.json index 1c89489..9e27039 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@rustle/mp-store", - "version": "0.1.1", + "version": "0.1.2", "description": "A lightweight wechat miniprogram state management library", "main": "dist/mpstore.common.js", "module": "dist/mpstore.esm.js", diff --git a/src/module.js b/src/module.js index a029316..16fd6f6 100644 --- a/src/module.js +++ b/src/module.js @@ -4,8 +4,9 @@ import { isPlainObject, } from './utils' -// a. can't delete module, if module is created -// b. modules allow nesting +// a. modules allow nesting +// b. can't delete module, if module is created +// c. can't create new module in setter function export const MODULE_FLAG = Symbol('module') export function isModule (m) { diff --git a/src/store.js b/src/store.js index 3a88fdf..badbfcf 100644 --- a/src/store.js +++ b/src/store.js @@ -315,13 +315,14 @@ export class Store { ) // need deep clone, otherwise the `data.global` on the back of the component cannot be changed. - createState = () => clone(mapObject(defineObject, fn => { - if (namespace === null) { - return fn(store.state) + if (namespace === null) { + createState = () => clone(mapObject(defineObject, fn => fn(store.state))) + } else { + createState = () => { + const module = this.getModule(namespace, `\n\n --- from [${namespace}] of useState.`) + return clone(mapObject(defineObject, fn => fn(module, store.state))) } - const module = this.getModule(namespace, `\n\n --- from [${namespace}] of useState.`) - return fn(module, store.state) - })) + } } // get state used by the current component