單項資料繫結、雙向資料繫結及其原理(髒檢查)
參考文章:
https://segmentfault.com/q/1010000002511449/a-1020000002514653
單向資料繫結:指的是我們先把模板寫好,然後把模板和資料(資料可能來自後臺)整合到一起形成HTML程式碼,然後把這段HTML程式碼插入到文件流裡面。
單向資料繫結缺點:HTML程式碼一旦生成完以後,就沒有辦法再變了,如果有新的資料來了,那就必須把之前的HTML程式碼去掉,再重新把新的資料和模板一起整合後插入到文件流中。
雙向資料繫結:資料模型(Module)和檢視(View)之間的雙向繫結。
使用者在檢視上的修改會自動同步到資料模型中去,同樣的,如果資料模型中的值發生了變化,也會立刻同步到檢視中去。
雙向資料繫結的優點是無需進行和單向資料繫結的那些CRUD(Create,Retrieve,Update,Delete)操作
雙向資料繫結最經常的應用場景就是表單了,這樣當用戶在前端頁面完成輸入後,不用任何操作,我們就已經拿到了使用者的資料存放到資料模型中了。
目前。實現雙向資料繫結的前端框架主要有AngularJS,VueJS等
不過,我總感覺雙向資料繫結的應用場景非常有限。 backbonejs不實現雙向資料繫結的解釋:大概的意思就是雙向資料繫結在實際的運用中很少,沒必要
"Two way data-binding" is avoided. While it certainly makes for a nifty demo, and works for the most basic CRUD, it doesn't tend to be terribly useful in your real-world app. Sometimes you want to update on every keypress, sometimes on blur, sometimes when
the panel is closed, and sometimes when the "save" button is clicked. In almost all cases, simply serializing the form to JSON is faster and easier. All that aside, if your heart is set, go for it.
髒檢查:
在angular中,他沒有辦法判斷你的資料是否做了更改, 所以它設定了一些條件,當你觸發了這些條件之後,它就執行一個檢測來遍歷所有的資料,對比你更改了地方,然後執行變化。這個檢查很不科學。而且效率不高,有很多多餘的地方,所以官方稱為髒檢查。l
Angular defines a concept of a so called digest cycle. This cycle can be considered as a loop, during which Angular checks if there are any changes to all the variables watched by all the $scopes. So if you have $scope.myVar defined in your controller and this variable was marked for being watched, then you are explicitly telling Angular to monitor the changes on myVar in each iteration of the loop.
This "digest
"
is also called "dirty checking", because, in a way, it scans the scope for changes. I cannot say if it's for better or for worse than observable pattern. It depends on your needs.
Some links: