Knockout $ parental doubt when using "c" to set context
I have a 3 level nested model like this
WebsiteViewModel => MenuViewModel => MenuEntryViewModel
WebsiteViewModelis the root model. Now, in the html template intended for MenuEntryViewModel, I set the binding context in MenuEntryViewModel using "with" as follows
<div id="contextSetter" data-bind="with: menuViewModel.menuEntryViewModel">
<div data-bind="event: {'hidden.bs.modal': function() {console.log($parent);}}">
...
</div>
</div
The above event binds unexpectedly logs WebsiteViewModel instead of MenuViewModel
So, if the binding context is currently menuViewModel.menuEntryViewModel , then the parent $ does not point to menuViewModel , it points to WebsiteViewModel (the root model in this case). Although I can use a workaround for this, I think $ parent should point to the MenuViewModel . Any comments on this behavior?
This is by design because you are clinging with: menuViewModel.menuEntryViewModeltogether, the parent context of the two elements together WebsiteViewModel.
Check out these samples sent by @Jeroen:
Nested structure
menuViewModel.menuEntryViewModel , , $parent WebsiteViewModel.
<div id="contextSetter" data-bind="with: menuViewModel.menuEntryViewModel">
<div data-bind="click: function() {console.log($parent);}">
click me to see console.log
</div>
</div>
JS
var websiteViewModel = {
txt: 'website',
menuViewModel: {
txt: 'menu',
menuEntryViewModel: {
txt: 'entry'
}
}
};
ko.applyBindings(websiteViewModel);
console.log($parent.menuViewModel), , , .
, $parent .
<div id="contextSetter" data-bind="with: menuViewModel">
<div data-bind="click: function() {console.log($parent);}">
top-click-me to see console.log
</div>
<div id="subContextSetter" data-bind="with: menuEntryViewModel">
<div data-bind="click: function() {console.log($parent);}">
click me to see console.log
</div>
</div>
</div>
JS
var websiteViewModel = {
txt: 'website',
menuViewModel: {
txt: 'menu',
menuEntryViewModel: {
txt: 'entry'
}
}
};
ko.applyBindings(websiteViewModel);