我正在使用knockout foreach绑定来绑定div。但是,当我点击按钮时,新模型不会被创建,模型会不断扩展。我希望我的数据只能被绑定一次,而不是一次又一次。我在做什么错。这是Here is a demo of problem
function bindValues() {
var obj1 = { Name: ko.observable("location & size") };
var obj2 = { Name: ko.observable("font") };
var obj3 = { Name: ko.observable("border lines + fills") };
var obj4 = { Name: ko.observable("alignment + padding") };
var model = new Object({
Styles: ko.observableArray()
});
model.Styles.push(obj1);
model.Styles.push(obj2);
model.Styles.push(obj3);
model.Styles.push(obj4);
ko.applyBindings(model, document.getElementById("style-accordion"));
}
答案 0 :(得分:2)
因为每次调用bindValues时都会调用ko.applyBindings
。在您的情况下,此函数只应调用一次。
我建议您在ViewModel中移动bindValues
,如下所示:
var model = {
Styles: ko.observableArray(),
bindValues: function() {
var obj1 = { Name: ko.observable("location & size") };
var obj2 = { Name: ko.observable("font") };
var obj3 = { Name: ko.observable("border lines + fills") };
var obj4 = { Name: ko.observable("alignment + padding") };
model.Styles.push(obj1);
model.Styles.push(obj2);
model.Styles.push(obj3);
model.Styles.push(obj4);
}
};
ko.applyBindings(model);
答案 1 :(得分:2)
因为你一次又一次地将值推送到你的observableArray 每次调用applyBindings时,只需要应用一次绑定并覆盖数组
var model = new Object({
Styles: ko.observableArray()
});
ko.applyBindings(model, document.getElementById("style-accordion"));
function bindValues() {
var obj1 = { Name: ko.observable("location & size") };
var obj2 = { Name: ko.observable("font") };
var obj3 = { Name: ko.observable("border lines + fills") };
var obj4 = { Name: ko.observable("alignment + padding") };
// override instead of push
model.Styles([obj1,obj2,obj3,obj4]);
}