首页 > 解决方案 > 创建新的 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);

标签: javascriptarraysknockout.js

解决方案


你只需要制作它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>


推荐阅读