问题
i have two view models and i want applybindings one view modek is Div specific and the other one is full page
var profileModel = {
first: ko.observable("Bob"),
last: ko.observable("Smith")
};
var shellModel = {
header: ko.observable("Administration"),
sections: ["profile", "settings", "notifications"],
selectedSection: ko.observable()
};
ko.applyBindings(shellModel);
ko.applyBindings(profileModel, document.getElementById("profile"));
回答1:
Hi @Jairam you can make a object with two view model and applybindings to object:
var profileModel = {
first: ko.observable("Bob"),
last: ko.observable("Smith")
};
var shellModel = {
header: ko.observable("Administration"),
sections: ["profile", "settings", "notifications"],
selectedSection: ko.observable()
};
var viewModel = {
subModelA: profileModel ,
subModelB: shellModel
};
ko.applyBindings(viewModel);
回答2:
You can't call ko.applyBindings(...) to the same parent element or even a child element within the same parent.
When you call ko.applyBindings(shellModel), you're binding your model to the entire DOM, and later, you start other bindings in a child element of your same document.
If you want to do so, merge both view models into one and execute a ko.applyBindings(mergedModel) and it should work in your scenario. Or call ko.applyBindings(...) for shellModel to a concrete element which shouldn't be a parent of profile.
回答3:
You can try something like this, it sort of merges the two viewmodels. Sort of like inheritance, viewmodel2 inherits all of viewmodel1's attributes.
function viewModel1() {
var self = this;
self.vm1Alert = function() {
alert('Model 1 stuff')
};
}
function viewModel2() {
var self = this;
viewModel1.call(self);
self.vm1Alert(); //from the first viewmodel
alert('Model 2 stuff');
}
ko.applyBindings(new viewModel2());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
来源:https://stackoverflow.com/questions/29294373/iam-unable-to-applybindings-in-knockout-is-this-correct-approach