Knockout学习笔记之二($root,$parent及$data的区别)
生活随笔
收集整理的這篇文章主要介紹了
Knockout学习笔记之二($root,$parent及$data的区别)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以下是我從Google上找到的一個例子,非常生動形象,我修改了部分代碼,具體內容如下:
對于$root 與$parent的區別:
- $root?refers to the view model applied to the DOM with?ko.applyBindings;
? ? ? ? 譯:$root 是指ViewModel所應用于ko.applyBindings時所使用的DOM;
- $parent?refers to the immediate outer scope;
?譯:$parent 是指當前DOM元素直接的外部父類(只有一層);
Or, visually, from?$data's perspective:
?
?
Or, in words of?the relevant documentation:
- $parent: This is the view model object in the parent context, the one immeditely outside the current context.
- $root: This is the main view model object in the root context, i.e., the topmost parent context. It’s usually the object that was passed to?ko.applyBindings. It is equivalent to?$parents[$parents.length - 1].
對于三者的區別($root,$parent及$data):
?
?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head><title></title><script type="text/javascript" src="knockout-3.4.0.js"></script><style>th, td {padding: 10px;border: 1px solid gray;}</style><script type="text/javascript">window.onload = function () {vm.mainPerson(grandpa);grandpa.children.push(daddy);daddy.children.push(son1);daddy.children.push(son2);ko.applyBindings(vm);}var Person = function (name) {var self = this;self.name = ko.observable(name);self.children = ko.observableArray([]);}var ViewModel = function () {var self = this;self.name = 'root view model';self.mainPerson = ko.observable();}var vm;vm= new ViewModel(),grandpa = new Person('grandpa'),daddy = new Person('daddy'),son1 = new Person('marc'),son2 = new Person('john');</script><script type="text/html" id="person"><tr><td data-bind="text: $root.name"></td><td data-bind="text: $parent.name"></td><td data-bind="text: $data.name"></td></tr><!-- ko template: { name: 'person', foreach: children } --><!-- /ko --></script><table><tr><th>$root</th><th>$parent</th><th>$data</th></tr><!-- ko template: { name: 'person', data: mainPerson } --><!-- /ko --></table> </head> <body> </body> </html>View Code
具體頁面呈現:
The?$root?is always the same. The?$parent?is different, depending on how deeply nested you are.
譯:$root經常是相同的,而$parent是不同的,而這種不同主要取決于你嵌套的深度。
?
總結
以上是生活随笔為你收集整理的Knockout学习笔记之二($root,$parent及$data的区别)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手机就能穿越历史!腾讯宣布将复现敦煌藏经
- 下一篇: 网店推好评返现卡被罚1万元!你会因为红包