Access data from a view model

You know that it has been quiet for too long, right ?; -)

I have a basic model. Inside the view, I use the binding layout to load the subview, which is “standalone” as much as what is displayed on it.

<div data-bind="compose: articleSection"></div> 

And "articleSection" is just observable, containing a string:

 var articleSection = ko.observable('viewmodels/lt_articleRead'); 

... because depending on the actions of the user, I might want a different view / model to load in this div.

In my main view model, I also have an observable "articleSelected":

 var articleSelected = ko.observable(true); 

... which is set when the article is selected from the list.

Inside my subview (lt_ArticleRead) I have two divs that can be displayed. One if articleSelected is false and one if true:

 <div id="articleSelected" data-bind="visible: articleSelected()"> ... </div> <div id="articleNotSelected" data-bind="visible: articleSelected()"> <p>Please select an article from the list on the left or create a new one</p> </div> 

I tried using "$ root.articleSelected ()" and "$ parent.articleSelected" to access the observable from the main model, but it does not work. Do I have to “require” a parent view model in a sub in order for this to work correctly?

+4
source share
1 answer

You need to set preserveContext:true in your binding layout.

 <div data-bind="compose: { model: articleSection, preserveContext: true }"></div> 

From the documentation (highlighted by me by me):

Whenever a composition is created, an isolated binding context is created around the created presentation and presentation model. So, from within this view, you cannot go outside to another model object . We believe that this is really important for encapsulation, because we saw that some really bad architectural things happen when you can “accidentally” refer to things outside the scope. As a result, everything is encapsulated by default. If you want, you can set preserveContext:true to bind to “connect” the new composition to its parent element and allow movement up the tree inside the child composition , but this is not the default value.

+5
source

Source: https://habr.com/ru/post/1500907/


All Articles