Use of two models of viewing of knockouts for one page

I am creating two knockout presentation models.

$.getJSON("/api/administrators", function (data) { var AccessViewModel = { administrators: ko.observableArray(data) }; ko.applyBindings(AccessViewModel); }); $.getJSON("/api/roles", function (data) { var RolesViewModel = { definedRoles: ko.observableArray(data) }; ko.applyBindings(RolesViewModel); }); 

I can get information from administrators in a view, but I canโ€™t get any of the defined Roles. When I add a warning inside the .getJSON function for roles, it returns data. There seems to be something wrong between creating the RolesViewModel and when I call it like this:

 <ul data-bind="foreach: definedRoles"> <li data-bind="text: name"></li> </ul> 

Can someone point me in the right direction?

+4
source share
3 answers

ko.applyBindings can only be called once for each section. If you do not pass the second parameter, the section is a whole page. If you have a specific section, such as a DIV , you should pass it as the second parameter.

Or, you can create one view model for a page with a property for both lists and simply link your page to this single view model. I recommend this approach. This code might look like this:

 var ViewModel = function() { this.administrators = ko.observableArray([]); this.definedRoles = ko.observableArray([]); }; var vm = new ViewModel(); ko.applyBindings(vm); $.getJSON("/api/administrators", function (data) { vm.administratos(data); }); $.getJSON("/api/roles", function (data) { vm.definedRoles(data); }); 

Remember, since ko.applyBindings only needs to be called once, you must do this as soon as possible. Calling from ajax methods is usually a bad idea for several reasons. First, the ajax method can no longer be reused as an update call; and two, the other functions of the page must wait for the ajax method to return in order to start working.

+8
source

Tyrsius answer is correct, but for future reference, you can link two different presentation models to the same page. You will need to bind models, for example

 ko.applyBindings(wallView,$("#WallKo")[0]); 

and wrap the html with a div with selected Id ie

 <div id = "WallKo"> <div data-bind="foreach:posts"> ..... </div> </div> 

Then you can have as many viewing models as you want for each page.

+7
source

Thanks for the example of HOW to bind a model to a specific div. Very useful

0
source

All Articles