Last active
April 7, 2017 11:09
-
-
Save jas0ncn/541e5ed6f73d049dbf80d2e344cdb7cd to your computer and use it in GitHub Desktop.
Store for wxapp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Object deepclone | |
* @param {Object} obj the object need clone | |
*/ | |
function deepclone (obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj | |
} | |
const newObj = {} | |
Object.keys(obj).forEach(v => { | |
if (typeof obj[v] === 'object' && obj[v] !== null) { | |
newObj[v] = deepclone(obj[v]) | |
} else { | |
newObj[v] = obj[v] | |
} | |
}) | |
return newObj | |
} | |
// a store for wxapp | |
class Store { | |
/** | |
* constructor | |
* @param {Object} initData 初始化数据 | |
*/ | |
constructor (initState = {}) { | |
if (typeof initState !== 'object' || initState === null) { | |
throw new TypeError('[Store] Init state must be a object.') | |
} | |
this._state = deepclone(initState) | |
this.state = this._hookState(this._state) | |
} | |
/** | |
* 禁止直接修改 | |
* @param {Object} _state | |
*/ | |
_hookState (_state) { | |
const state = {} | |
Object.keys(_state).forEach(key => { | |
if (typeof _state[key] === 'object' && _state[key] !== null) { | |
_state[key] = this._hookState(_state[key]) | |
} else if (typeof _state[key] === 'function') { | |
throw new TypeError('[Store] state cannot save function.') | |
} | |
// setter hook | |
Object.defineProperty(state, key, { | |
enumerable: true, | |
configurable: true, | |
get () { | |
return _state[key] | |
}, | |
set (newVal) { | |
throw new TypeError('[Store] mutate state failed. Use .mutate() to mutate state') | |
} | |
}) | |
}) | |
return state | |
} | |
/** | |
* mutate state | |
* @param {Function} fn | |
*/ | |
mutate (fn) { | |
this._state = deepclone( | |
fn( | |
deepclone(this._state) | |
) | |
) | |
this.state = this._hookState(this._state) | |
} | |
} | |
module.exports = Store |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment