背景
在ASP。NET MVC中,我们有ViewModel
模式来显示视图中域对象中的选定数量的属性。有时,这些特性是基于其他特性计算的,例如:
public int Total {
get {
return this.Count * this.Price;
}
}
问题
我试图在Angular
中遵循类似的模式-给定来自服务器的JSON对象,我将其转换为一个类(我的域对象),然后创建一个专门的ViewModel
类,该类的属性基于其他属性计算,例如:
public get total: number {
return this.count * this.price;
}
问题是,当我将这样的属性绑定到模板时,Angular会不断地对其进行评估,我担心它可能会影响性能。这种连续评估是合理的,因为属性的值必须对"依赖"属性的变化做出反应。因此,如果"计数"或"价格"发生变化,我确实需要显示"总计"的新值。
但我希望根据需要更新total的值,而不是强迫Angular不断评估它。
我还有什么其他选择?
您的担忧是有效的。你不应该那样做。
只需将结果分配给一个字段,然后绑定到该字段即可。
每次运行更改检测时,Angular都会计算绑定表达式。您可以尝试使用ChangeDetectionStrategy.OnPush
或ChangeDetectorRef.detach()
来减少更改检测运行的次数,但最好使用字段
使用字段进行更改检测非常有效。
_count:number;
set count(value:number) {
this._count = value;
this.calcTotal();
}
get count() {return this._count;}
_price:number;
set price(value:number) {
this._price = value;
this.calcTotal();
}
get price() {return this._price;}
_total:number;
get total() {return this._total;}
_calcTotal(): number {
this._total = this.count * this.price;
}