我一直在处理重构我的angularjs应用程序以使用controllerAs并想看看我是否可以摆脱所有$ scope。$ watch函数。我通过使用getter和setter定义属性来管理这个,并且效果很好。卡住的地方是$ watchCollection的替代品。作为一个例子,我有一个指定属性的指令叫做" params"。这是一个具有子属性的对象。在我使用$ scope。$ watch(' params',function(){...},true)或使用$ watchCollection之前。现在,由于在更改子参数时未设置实际对象,因此不会调用setter。以下是我提出的解决方案,但我希望有更好的东西。另外,我知道如果需要,我仍然可以使用$ watch和$ watchCollection。只是看看是否有办法避免它。 params属性是动态的,因此不会提前知道子属性。
var dynamicVariables = {};
function defineChildProperty(obj,i){
if(!dynamicVariables.hasOwnProperty(i)){
dynamicVariables[i] = obj[i];
}
Object.defineProperty(obj,i,{
get:function(){return dynamicVariables[i];},
set:function(val){
if(obj[i] === val){
return;
}
dynamicVariables[i] = val;
fetchChart();
}
});
}
function getChildProperties(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)){
defineChildProperty(obj,i);
}
}
}