Reputation: 17373
I'm using a knockout.js on my project to bind model to view. Basically, on document.ready function I use the code below:
var viewModel = {
firstName: ko.observable("John")
listofChildren=ko.observablearray()
};
ko.applyBindings(viewModel);
dataService.getChildren(viewModel); // This is no good need to move to partial view
i can use the above viewModel on most of pages. However, I've a requirement that for one partial view we call third party web service by Jquery and populate the listOfChildren property above.
Problem is that at the moment the call to webservice happens on document.ready which means every page refresh makes call to web service. I would like to make a call only if user loads the partial view.
I tried to move the call to third party webservice on partial view page but it shows viewModel is null.
dataService.getChildren(viewModel); //where dataService is a function which uses ajax call to webservice and populates the listofChildren array.
Could someone please help me how best above can be achieved?
Upvotes: 0
Views: 321
Reputation: 3192
There are two reasons why moving the call to getChildren
wasn't able to find viewModel
after moving it to the partial view:
viewModel
is scoped to the document.ready
function, and isn't visible outside of theregetChildren
was happening before the viewModel
was createdHere is what I would recommend: Leave the getChildren
call inside document.ready
, but only execute it if the partial view exists by searching for something that only exists in the partial view. If you find it, then load the children.
if ($('#SomethingInPartialView').length) {
dataService.getChildren(viewModel);
}
Upvotes: 1