我有这个动态填充的复选框控件
{ code: "001" , name: "Parker"},
{ code: "002" , name: "Sheaffer"},
{ code: "003" , name: "Mont Blanc"}
假设可观察数组GET(AllPens)
"Pens": [{
"PenType": "001",
"Order": false
}, {
"PenType": "002",
"Order": true
}]
我必须回复一个已检查元素的数组 -
function Pen(type, checked) {
var self = this;
self.PenType = ko.observable(type);
self.IsChecked = ko.observable(false);
}
我有一个粗略的想法是存储已检查的Pen代码,如果在对象中有缺陷 - 新笔(' 001',true)
self.Pens= ko.computed(function()
{
var selectedPens = [];
ko.utils.arrayForEach(self.Pen(), function (pen) {
if(pen.IsChecked())
selectedPens.push(pen);
});
return selectedPens;
});
如何将复选框值绑定到对象上的Knockout observableArray?
如果我弄清楚以上情况,我相信以下内容应该有效。
CREATE TABLE "public"."bar" (
"bar" varchar(10) COLLATE "default" NOT NULL,
CONSTRAINT "bar_pkey" PRIMARY KEY ("bar")
);
CREATE TABLE "public"."foo" (
"foo" varchar(5) COLLATE "default",
CONSTRAINT "foo_foo_fkey" FOREIGN KEY ("foo") REFERENCES "public"."bar" ("bar") ON DELETE NO ACTION ON UPDATE NO ACTION
);
我还在学习KO。任何帮助表示赞赏:)
答案 0 :(得分:3)
我设法让这个工作。
我没有动态地将键值对直接填充到Self.AllPens(),而是创建了一个将笔列表加载到对象中的函数
function Pen(type,name,checked) {
var self = this;
self.PenType= ko.observable(type);
self.Name = ko.observable(name);
self.IsChecked = ko.observable(checked || false);
}
循环检查下面的IsChecked -
self.Pens= ko.computed(function () {
var selectedPens = [];
ko.utils.arrayForEach(self.AllPens(), function (pen) {
if (pen.IsChecked()) {
selectedPens.push({
PenType: pen.penType,
Order: pen.IsChecked()
});
}
});
return selectedPens ;
});
答案 1 :(得分:0)
你的代码应该是这样的
self.checkedPens = function(pen) {
var isChecked = pen.order === "true";
if (pen.penType !== null && isChecked) {
self.Pens.push({
PenType: pen.penType,
Order: isChecked
});
}
};