[英]How to force applyBindings in Knockout JS
I want to refresh model binding for my page. 我想为我的页面刷新模型绑定。 As says documentation I use applyBindings method. 正如文档所述,我使用applyBindings方法。 Also I need to use few viewModels on a page. 另外,我需要在页面上使用少量viewModel。 To do it I use object-wrapper + "with" keyword on binding: 为此,我在绑定时使用object-wrapper +“with”关键字:
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: 1)工作正常:
$("#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: 2)不起作用:
$("#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. 我也尝试使用“ko.cleanNode()”方法,但它也不起作用。 Full sample of code stored at http://jsfiddle.net/eN8dq/2/ 存储在http://jsfiddle.net/eN8dq/2/的完整代码示例
Can you suggest me true way how I can add additional view model on a page? 您能否建议我如何在页面上添加其他视图模型? Thank you! 谢谢!
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());
My solution for this case: https://github.com/sergun/Knockout-MultiModels 我对这种情况的解决方案: https : //github.com/sergun/Knockout-MultiModels
Any comments? 任何意见?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.