javascript - 创建新的 KO.observable 数组并从数组对象中填充它
问题描述
是否可以创建一个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);
解决方案
你只需要制作它items
而不是quotesarray
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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr><th>name</th><th>address</th></tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
</tr>
</tbody>
</table>
推荐阅读
- c++ - Visual Studio - SQLDriverConnect 失败(返回 SQL_ERROR)
- docker - 在 gitlab ci 中查找在 docker-compose 中运行的容器的 url/ip
- arrays - 从 C 中的源字符串的开头提取子字符串时出错
- r - 如何有效地检查 R 中特定值的检查变量并标记包含它的行?
- java - 如何在一个文本文件中存储多个用户名
- git - 本地存储库是否需要 Git LFS?
- php - 使用 json_decode 格式化数据输出
- ms-access - 格式化重复值的单元格以使其不可见
- python - 如果目录不存在,则在 Pillow 中创建目录
- python - 如何使用 python 运行 C 文件?