Reputation: 386
I want to refresh model binding for my page. As says documentation I use applyBindings method. Also I need to use few viewModels on a page. To do it I use object-wrapper + "with" keyword on binding:
ko.applyBindings({ model1: {...}, model2: {...} });
<div data-bind="with: $root.model1"> ... </div>
<div data-bind="with: $root.model2"> ... </div>
It works fine until I don't use dynamic bindings update. If I try to add additional viewmodels on a page, it doesn't work :(
Few pieces of code:
1) Works fine:
$("#b1").click(function () {
ko.applyBindings({
myModel1: {
MyText: ko.observable("Some text")
},
myModel2: {
MyText: ko.observable("Some text")
}
});
});
$("#b2").click(function () {
ko.applyBindings({
myModel1: {
MyText: ko.observable("Some other text")
},
myModel2: {
MyText: ko.observable("Some other text 2")
}
});
});
2) Doesn't work:
$("#b1").click(function () {
ko.applyBindings({
myModel1: {
MyText: ko.observable("Some text")
}
});
});
$("#b2").click(function () {
ko.applyBindings({
myModel1: {
MyText: ko.observable("Some other text")
},
myModel2: {
MyText: ko.observable("Some other text 2")
}
});
});
As I understand, we have no way to bind additional view models in such manner. I also tried to use "ko.cleanNode()" method, but it doesn't work too. Full sample of code stored at http://jsfiddle.net/eN8dq/2/
Can you suggest me true way how I can add additional view model on a page? Thank you!
Upvotes: 1
Views: 2689
Reputation: 386
My solution for this case: https://github.com/sergun/Knockout-MultiModels
Any comments?
Upvotes: 1
Reputation: 1956
try not to force bindings, but change value for already bound model:
var viewModel = function () {
var self = this;
self.myModel1 = ko.observable( {
MyText: ko.observable("Some other text")
});
self.myModel2 = ko.observable({
MyText: ko.observable("Some other text 2")
});
self.clickAction = function() {
//do the trick of assigning value
self.myModel1 ({
MyText: ko.observable("Some another text")
});
};
};
ko.applyBindings(new viewModel());
Upvotes: 2