标签:
在看完这个文章前,先别看官方指南。看完文章再去看指南会更清晰。因为本文章是angular的简易实现。
为了了解Scope的原理,可以先试着实现一个Scope。
最初的想法是:我们需要监测Scope对象的一个属性,当这个属性发生变化的时候我们做点什么。
所以按照angular的实现原理是这样的:
所以现在可以根据以上想法写代码了。
function Scope(){ this.$$watcheres=[]; }; Scope.prototype.$watch=function(watchFn,listenFn){ var watcher={ watchFn:watchFn, listenFn:listenFn, last:‘‘ }; this.$$watcheres.push(watcher); }; Scope.prototype.$digest=function(){ var self=this; _.forEach(self.$$watcheres,function(watcher){ if(watcher.watchFn(self)!=watcher.last){ watcher.listenFn(self); } else{ console.log("没检测到有变化"); } watcher.last=watcher.watchFn(self); }); }; scope1=new Scope(); scope1.name="王吉"; scope1.$watch(function(scope){ return scope.name; },function(scope){ console.log(‘原来的值检测到有改变,现在是:‘+scope.name); }); scope1.$digest();//第一次运行,会检测到有改变,因为last初始化的时候是空的。 scope1.$digest();//第二次运行,不会有改变,所以什么都不做。 scope1.name="帅哥"; scope1.$digest();//第三次运行,会有改变,当然会有改变。
在线代码在这里:http://jsbin.com/barikutuni/edit?js,console
标签:
原文地址:http://www.cnblogs.com/oukichi/p/5161965.html