Angularjs的$watch相信你们都知道,并且也常常使用,甚至,你还在为它的某些行为感到恼火。好比,一进入页面,它就会调用一次,我明明但愿它在我初始化以后,值再次变更才调用。这种行为给咱们带来许多麻烦。而咱们今天就是要优化$watch的写法,来解决这些问题。数组
$scope.$watch('xxx',function(newVal,oldVal){ if(newVal === oldVal || oldVal==undefined){ //不执行代码 }else{ //执行你的代码 }})
为何这么写?听我慢慢道来。异步
首先,咱们作一个测试。函数
$scope.$watch('name',function(newVal,oldVal){ console.log('oldVal',oldVal) //undefined console.log('newVal',newVal) //undefined if(newVal === oldVal || oldVal==undefined){ //不执行代码 }else{ //执行你的代码 } })
咱们监听name的改变,一开始进来,没有初始化时,都为undefined。测试
而后,咱们先定义name优化
$scope.name="张三"; $scope.$watch('name',function(newVal,oldVal){ console.log('oldVal',oldVal) //张三 console.log('newVal',newVal) //张三 if(newVal === oldVal || oldVal==undefined){ //不执行代码 }else{ //执行你的代码 }})
能够看到,一开始进来就都是张三。
由此可知,当监听器函数初始化时,newVal和oldVal老是相等的,因此,此时咱们能够判断两个值是否相等,来执行咱们想要的操做。code
为何要判断oldVal==undefined?由于,当咱们给name赋值的时候,会有一个undefinde变为有值的过程。因此当你不想在第一次赋值时,就执行方法,这么干就对了。
咱们给name的赋值套一个timeout,模仿异步调用,在实际项目中,咱们的name一般都是从接口获取的。blog
$timeout(function(){ $scope.name="张三"; },500)
而后,你再观察一下watch接口
$scope.$watch('name',function(newVal,oldVal){ console.log('oldVal',oldVal) //undefined console.log('newVal',newVal) //张三 if(newVal === oldVal || oldVal==undefined){ //不执行代码 }else{ //执行你的代码 }})
以上就是watch须要注意的一些事项。而后,咱们接下来讨论的是如何监听数组的变化,这就要用到另外一个监听方法,$watchCollection。get
你们,能够运行如下代码,
https://codepen.io/hanwolfxue/pen/XYyVYv?editors=1010
出来的样子长这样
it
好好观察一下watch和watchCollection的行为,能够发现watch是监听不到数组的变化的,因此,若是你要监听的是一个数组的话,请用watchCollection代替watch.
以上两点就是今天要说的优化,固然$watch还有不少其余内容,感兴趣的小伙伴能够继续研究一下。