我真的很新,我遇到了列表绑定的问题。
var RequiredItemLine = function () {
var self = this;
self.editable = ko.observable(0);
self.desc = ko.observable();
self.key = ko.observable();
self.requireditems = ko.observableArray([
{ desc: "Boarding of exposed wall openings in the vicinity of ...", key: "233" },
{ desc: "Call in manufacturers to initiate repairs on ...", key: "242" },
{ desc: "Call in specialist restorers/recoverers for ...", key: "244" },
{ desc: "Dispatch items for repair (schedule enclosed)", key: "243" },
{ desc: "Drying and cleaning of contents comprising ...", key: "240" },
{ desc: "Drying and protective oiling of water affected equipment", key: "241" },
{ desc: "Drying out of the affected areas of the premises", key: "235" },
{ desc: "Removal and repackaging of stock comprising ...", key: "239" },
{ desc: "Removal of agreed vulnerable contents to a place of safety (schedule enclosed) ", key: "236" },
{ desc: "Segregation of affected and unaffected stock comprising ...", key: "238" },
{ desc: "Temporary covering of roof to reinstate water tight integrity ", key: "234" },
{ desc: "Temporary guarding of affected area", key: "237" },
{ desc: "Temporary shoring of affected structure", key: "232" }]);
self.selectedItem = ko.observable(self.requireditems()[0]);
self.selectedItem.subscribe(function (newValue) {
var li = "<li>" + newValue.desc + "</li>";
$('#items').append(li);
});
};
var RequiredItem = function () {
var self = this;
self.requireditemSelection = ko.observableArray([]); // Put one line in by default
self.requireditemlines = ko.observableArray([]);
// Operations
self.addRequiredItem = function () { self.requireditemSelection.push(new RequiredItemLine()) };
self.RemoveRequiredItem = function (line) { self.requireditemSelection.remove(line) };
};
ko.applyBindings(new RequiredItem());
请看这个小提琴。 JSFiddle Link,在页面中包含一个添加选择列表的按钮,当点击一个按钮时,新的选择列表将被添加到DOM。当用户从一个选择列表中选择项目时,所选项目应该单独显示,并且当用户改变时,已经显示在DOM中的所选项目必须根据选择而改变,而不是附加新的li。 / p>
请看第二张图片,我不想显示另一个列表项,而不是我想要更改当前添加的项目。
答案 0 :(得分:3)
我觉得你很亲密。我不是100%确定我是否正确理解了您的问题,我已将您的问题解释为“想要在只读列表中显示所有选定的项目”。
请参阅updated fiddle,其中我只是将ul
更改为:
<ul data-bind='foreach: requireditemSelection'>
<li data-bind="text: selectedItem().desc"></li>
</ul>
您无需手动创建li
项并将其添加到DOM。让KO为您处理,并且数据绑定只读项目。