【发布时间】:2018-12-28 07:55:34
【问题描述】:
是否可以创建一个ko.observable 数组并使用数组对象填充它?
我的目标是创建一个 ko.observable 数组,其中包含原始数组中的所有描述/对象。
//Sample data the original data is coming from an socket query and being push on the array("people")
var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "family"
},
{
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "friend"
}
];.
var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "family"
},
{
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "friend"
}
];
var quotesarray = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
}
}.bind(this);
};
ko.applyBindings(new quotesarray(people));
console.log(people);
【问题讨论】:
-
你几乎可以做到,你遇到了什么问题?
-
@supercool 结果不敌
-
你介意保留代码并显示错误我可以帮你修补它。
-
@supercool jsfiddle.net/zo8ygfk4/4这里我只是做一个简单的
-
你应该遍历项目的 (jsfiddle.net/zo8ygfk4/7) 。 ko.applyBindings 将第一个参数作为 viewModel。由于您在第二个中没有提及任何参数,因此默认情况下它需要文档。
标签: javascript arrays knockout.js