以下是我从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是不同的,而这种不同主要取决于你嵌套的深度。