鸦杀's Blog

脏值检测(修改)

2015-12-09

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
var Scope=(function(){

/*
*脏值检测模块,依赖underScore.js
*/

function Scope(){
//储存监听器对象的数组
this.watchers = [];
this.watchList={};
}

//定义watch方法
Scope.prototype.watch = function(key,listenFn){
//私有,临时变量watch
var self = this,
_key=this.watchList[key],
watcher;

if(!_key){
this.watchList[key]=''+this.watchers.length;

watcher = {
watchFn : function(){
return self[key];
},
listenFn : listenFn
};

//添加到监听数组
this.watchers.push(watcher);
}
}

Scope.prototype.getWatchIndex=function(key){
var i= this.watchList[key];
if(typeof i==="undefined"){
i=-1;
}else{
i=+i;
}
return i;
};

//执行脏值检测
Scope.prototype.digest = function(){
var ttl = 10;
var dirty;
var self = this;
var digestOnce = function(){
var len = self.watchers.length;
var dirty;
for(var i = 0 ; i < len ; i++){
var watchObj = self.watchers[i];
var newValue = watchObj.watchFn(self);
var oldValue = watchObj.last;

if(!self.isEqual(newValue,oldValue)){
//值变化,执行监听函数
watchObj.listenFn(newValue,oldValue,self);
dirty = true;
}
watchObj.last = newValue;

}
return dirty;
}

do{
dirty = digestOnce();
ttl--;
}while(dirty && ttl > 0);

return self;
}

Scope.prototype.isEqual = function(value1,value2){
//判断对象
if (_.isObject(value1)) {
return _.isEqual( value1, value2 );
} else {
return value1 === value2 ||
( typeof value1 === 'number' &&
typeof value2 === 'number' &&
isNaN(value1) &&
isNaN(value2) );
}
}

Scope.prototype.set = function(key,value){
var self = this;
self[key] = value;
self.digest();
}

return Scope;
})();

var scope=new Scope();

scope.watch('arr1',function(){console.log("数组1变化了")});

scope.set('arr1',[2]);

扫描二维码,分享此文章