Javascript异步数据的同步处理方法

数据处理方法封装

var DataWatch=(function(){
            var gWatch={},cursor= 0,callback_key = 'callback',gMap={};
            var check=function(cursor,name){
                var _watcher=gWatch[cursor],itemCount = 0,resArr=[],flag=false;
                if(!!map){
                    return;
                }
                if(name && typeof (_watcher[name]) === undefined){
                    return;
                }
                for(var key in _watcher){
                    if(key === callback_key){
                        continue;
                    }
                    if(gMap[key]){
                        _watcher[key]=true;
                        resArr.push(map[key]);
                    }
                    itemCount++;
                }
                if(resArr.length === itemCount){
                    _watcher[callback_key] && _watcher[callback_key].apply(this,resArr);
                }
                resArr=null;
            };
            return {
                watch:function(name,callback){
                    //兼容watch单个内容
                    if(typeof(name) === 'string' ){
                        name=[name];
                    }
                    var _watcher={};
                    name.forEach(function(item){
                        _watcher[item]=false;
                    })
                    _watcher[callback_key]=callback;
                    cursor++;
                    gWatch[cursor]=_watcher;
                    check(cursor);
                },
                put:function(key,value){
                    gMap[key]=value;
                    for(var cursor in gWatch){
                        check(cursor,key);
                    }
                }
            }
        })()

使用方法可以下面这样

func1.ajaxSucc:DataWatch.put(key1,value1)
func2.ajaxSucc:DataWatch.put(key2,value2)
func3.ajaxSucc:DataWatch.put(key3,value3)

DataWatch.watch([key1,key2],function(value1,value2){
})

DataWatch.watch([key1,key3],function(value1,value3){
})

 

posted @ 2015-12-19 22:04  GongQi  阅读(1187)  评论(0编辑  收藏  举报