redux核心代码设计,总体遵循的原则:
1.取值只读
2.存值通道唯一
3.数据订阅
4.存储值改变通知

function Redux (conf) {
    var STATUS = {
        'READY': 0,         // 可读写
        'UPDATING': 1,      // 写入中,延时写
        'PUBLISHING': 2,    // 发布修改中,延时写
    };
    var storage = {
        // 数据区
        data: {},
        timer: null,
        updateDelay: conf.delay || 10,
        // 订阅区
        listeners: [],
        // 存储器状态
        statu: STATUS.READY,
    };
    function ReduxStore () {}
    ReduxStore.prototype.describ = function(map2storeFunc){
        if (storage.listeners.indexOf(map2storeFunc) < 0) {
            // 去重,防止重复订阅
            storage.listeners.push(map2storeFunc);
        }
    };
    ReduxStore.prototype.undescrib = function(map2storeFunc){
        var index = storage.listeners.indexOf(map2storeFunc);
        if (index > -1) {
            // 取消订阅
            storage.listeners.splice(index, 1);
        }
    };
    var _publish = function(){
        storage.listeners.forEach(function(listener){
            listener(ReduxStore.prototype.getState())
        });
        storage.statu = STATUS.READY;
    };
    ReduxStore.prototype.dispatch=function(name, val){
        if (storage.statu === STATUS.READY && storage.data[name] !== val) {
            storage.statu = STATUS.UPDATING;
            storage.data[name] = val;
            // 处理批量更新,防止分发订阅导致DOM频繁修改,主线程阻塞
            clearTimeout(storage.timer);
            storage.timer = setTimeout(_publish, storage.updateDelay);
        }
    };
    ReduxStore.prototype.getState=function(){
        return JSON.parse(JSON.stringify(storage.data));
    };
    return new ReduxStore()
}({});

以上代码基本实现了唯一可记录的数据源模型。
下一次,将在此基础上修改实现可扩展中间件部分(dispatch中间件)


zhfhz
188 声望1 粉丝

引用和评论

0 条评论