2017-03-16 38 views
0

這對我來說並不完全清楚談論這個的時候,這裏(模板語法部分)究竟由Angular2文檔中的「副作用」的意思,例如:
Angular2文檔中的「副作用」是什麼意思?

Avoid side effects 
As mentioned previously, evaluation of a template expression should have no visible side effects. The expression language itself does its part to keep you safe. You can't assign a value to anything in a property binding expression nor use the increment and decrement operators. 

Of course, the expression might invoke a property or method that has side effects. Angular has no way of knowing that or stopping you. 

The expression could call something like getFoo(). Only you know what getFoo() does. If getFoo() changes something and you happen to be binding to that something, you risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. In general, stick to data properties and to methods that return values and do no more. 

如何表達的評估可能有副作用,這可能對UI呈現或邏輯有什麼影響?

回答

2

它測量值綁定中的表達式應該只計算一個值並將其返回,但它們不應該修改其他變量的狀態。

相反,事件綁定中的表達式應該引起副作用。這就是爲什麼在調用事件偵聽器之後Angular運行更改檢測的原因。

參見https://en.wikipedia.org/wiki/Pure_function

1

像幾乎所有的語言,性能應該不會造成狀態的改變或執行任何長時間運行的任務。 見例如微軟的準則在這裏:https://msdn.microsoft.com/en-us/library/ms182181.aspx

考慮這一總體原則考慮,你看到的變化,跟蹤代碼在這裏:http://blog.angular-university.io/how-does-angular-2-change-detection-really-work/

正如你所看到的,變化檢測是相當直接的:檢查相等性,如果值不同,則將名爲「isChanged」的屬性設置爲true。現在

,假設如果一些屬性,如執行的東西會發生什麼:

  • Web的API調用
  • 更改其他屬性值
  • 由於不是冪等

我不知道確切的代碼,但更改跟蹤器應儘可能保持響應和簡單,以執行如此多的運行,這就是爲什麼建議將屬性保持簡單直接的原因即