我认为这可能更像是一个语言问题而不是框架问题,但这里有:
我在设置复选框的初始值时遇到问题。
我添加了jsFiddle
谢谢!
这是一个麻烦的代码:
var allPrices = [
{ month: 'January', prices: [ (3, true), (4, false), (4, false), (4, false)] },
{ month: 'February', prices: [(3, true), (4, false), (4, false), (4, false)] },
{ month: 'March', prices: [(3, true), (4, false), (4, false), (4, false)] }
]
//--Page ViewModel
var id = 1;
//--Set the structure for the basic price object
function Price(quote, isChecked) {
this.quote = ko.observable(quote);
this.valid = true;
if (isNaN(quote)) {
this.valid = false;
}
this.selected = ko.observable(isChecked);
this.id = id;
id++;
}
答案 0 :(得分:1)
使用(3, true)
语法,您正在使用Comma Operator而不是创建对象。
逗号运算符计算其第二个参数(在本例中为true
),因此它不会创建一个值为3的对象,并且正如您可能预期的那样为真。
您需要使用{}
创建对象,并且还需要一些属性名称,因此您需要将价格重写为:
prices: [
{ quote: 3, isChecked: true},
{ quote: 4, isChecked: false},
{ quote: 4, isChecked: false},
{ quote: 4, isChecked: false} ]
您需要将价格创建更改为
this.prices = ko.utils.arrayMap(prices, function (item) {
return new Price(item.quote, item.isChecked);
});
因为arrayMap
的回调函数具有参数:当前项,您可以从当前项访问quote
和isChecked
。