I am learning KnockoutJS, but I do not understand the difference between $root
and $parent
usage. Please see this jsfiddle, or the below code:
<div data-bind="foreach:mainloop">
$data Value: <span data-bind="text:$data.firstName"></span>
<span data-bind="text:$data.lastName"></span> --(1)
<br/>
$parent Value: <span data-bind="text:firstName"> </span>
<span data-bind="text:$parent.lastName"></span>
<br/>
$root Value: <span data-bind="text:firstName"></span>
<span data-bind="text:$root.lastName"></span>
<br/>
<hr/>
</div>
var mainLoopModel = function () {
var self = this; // Root Level scope
self.mainloop = ko.observableArray([{
'firstName': 'jhon'
}, {
'firstName': 'sam'
}]);
self.lastName = ko.observable('peters');
/*if you remove $data before lastName in note (1) you get undefined error because because mainloop dont have lastName root model has lastName so you have to access using parent or higher level */
}
ko.applyBindings(new mainLoopModel());
In the above code $root
and $parent
are both used for the same purpose: to refer outer scope variable. I just like to know is there any difference between the $root
and $parent
usages? If yes then please help me understand with a good example for correct usage.
They are similar but different:
$root
refers to the view model applied to the DOM withko.applyBindings
;$parent
refers to the immediate outer scope;Or, visually, from
$data
's perspective:Or, in words of the relevant documentation:
You'll only see a practical difference if you have view models nested more than one level, otherwise they will amount to the same thing.
It benefit is rather simple to demonstrate:
The
$root
is always the same. The$parent
is different, depending on how deeply nested you are.