时间:2021-07-01 10:21:17 帮助过:31人阅读
//TinyFlux.js
function createStore (store, ...args) {
if (!store) {
throw new Error('请定义store');
};
if (typeof store.init === 'function') {
store.init(args);
};
if (typeof store.actions !== 'function') {
throw new Error('actions应该是一个返回一个对象的function,对象里的方法都要用箭头表达式来书写,利用箭头表达式的this绑定。');
};
store.actions = store.actions();
if (store.subscriber || store.emit) {
throw new Error('不该存在subscriber和emit');
};
store.subscriber = [];
store.emit = function(argument) {
store.subscriber.forEach(component => component.reload());
};
return store;
}
function connect (store, def) {
return {
getInitialState: function(){
var state = {};
for (var i in def) {
try{
state[i] = eval('store.'+def[i]);
} catch(err) {
console.log(err);
}
};
return state;
},
reload: function() {
var state = {};
for (var i in def) {
try{
state[i] = eval('store.'+def[i]);
} catch(err) {
console.log(err);
}
};
this.setState(state);
},
componentDidMount: function(){
store.subscriber.push(this);
},
componentWillUnmount: function() {
store.subscriber.splice(store.subscriber.indexOf(this),1);
}
};
}
module.exports = {
createStore: createStore,
connect: connect
}