AngularJS$watch vs$watchCollection:哪一种性能更好?
对于查看对象范围变量,将AngularJS$watch vs$watchCollection:哪一种性能更好?,angularjs,angularjs-scope,angularjs-watch,Angularjs,Angularjs Scope,Angularjs Watch,对于查看对象范围变量,将$scope.$watch和objectEquality设置为true还是$scope.$watchCollection更好 对于视图中使用输入元素和ng model更新的$scope对象变量(如15个属性,一些嵌套的两层深),将对象相等设置为真时,$scope.$watch的情况有多糟?这是一件需要避免的大事吗 $watchCollection是更好的解决方案吗 我正在寻找轻松的胜利,以提高我的AngularJS应用程序的性能(我仍然停留在v1.2.2) //ctrl范
$scope.$watch
和objectEquality
设置为true还是$scope.$watchCollection
更好
对于视图中使用输入元素和ng model
更新的$scope
对象变量(如15个属性,一些嵌套的两层深),将对象相等设置为真时,$scope.$watch
的情况有多糟?这是一件需要避免的大事吗
$watchCollection
是更好的解决方案吗
我正在寻找轻松的胜利,以提高我的AngularJS应用程序的性能(我仍然停留在v1.2.2)
//ctrl范围变量
$scope.filters={
名称:“”,
信息:{test:'',foo:'',bar:'},
是的:''
//等等。。。
}
//手表?
$scope.$watch('filters',函数(newVal,oldVal){
if(newVal!==oldVal){
//使用更新的筛选器调用
}
},对);
//还是ctrl手表系列?
$scope.$watchCollection('filters',函数(newVal,oldVal){
if(newVal!==oldVal){
//使用更新的筛选器调用
}
});
//使用ng模型查看输入
//等等。。。
$watchCollection()
函数是
上述两种$watch()
配置。它比
$watch()函数;但是,它的价格远没有汽车贵
深度相等$watch()
函数。与$watch()
函数一样
$watchCollection()
通过比较物理对象引用来工作;
但是,与$watch()
函数不同,$watchCollection()
将
一级深,并执行额外的浅参考检查
集合中的顶级项
$watchCollection
针对矢量阵列[]
进行了优化,其中可以推送元素
而$watch
适用于关联数组对象{}
$watchCollection
不会监视深度变化,就像将objectEquality设置为false的监视一样
如果您已经知道深度的结构,您可以这样优化:
// ctrl watch ?
$scope.$watch('filters', function(newVal, oldVal) {
if(newVal !== oldVal) {
// call with updated filters
}
});
// ctrl watch ?
$scope.$watch('filters.info', function(newVal, oldVal) {
if(newVal !== oldVal) {
// call with updated filters
}
});
$watch()将由以下操作触发:
$scope.myArray = [];
$scope.myArray = null;
$scope.myArray = someOtherArray;
$watchCollection()将由上述所有内容触发,并且:
$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value
$scope.myArray[0].someProperty = "someValue";
$watch(…,true)将由上述所有内容触发,并且:
$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value
$scope.myArray[0].someProperty = "someValue";
还有一件事…
$watch()是当一个数组替换为另一个具有相同内容的数组时唯一激发的数组。例如:
$scope.myArray = ["Apples", "Bananas", "Orange" ];
var newArray = [];
newArray.push("Apples");
newArray.push("Bananas");
newArray.push("Orange");
$scope.myArray = newArray;
下面是一个示例JSFIDLE的链接,该示例使用所有不同的监视组合并输出日志消息来指示触发了哪些“监视”:
不确定您所说的$watchCollection(…,true)
是什么意思,因为该函数没有像$watch
@tamakisquare那样接受布尔参数(即objectEquality),我进行了更正和额外的更新以使其更清晰。包括更新JS提琴。@Luisprezphd-关于您的最新更新,$watchCollection()
也会被触发,因为$watch()
和$watchCollection()
都比较对象引用,而不是像$watch(…true)那样比较对象相等性
@tamakisquare您能否创建一个JS小提琴来说明这一点。根据我的回答,我在JS中看到了这个场景,$watchCollection()
没有触发。这个例子使用的是AngularJS 1.2.1。@Luisprezphd-我想我昨晚在尝试$watchCollection
时一定是和别的东西混在一起了,因为我现在不能像你说的那样用$watchCollection()
重现它。对不起,误报了。我的错。