如何使用Knockout连接Observable Array中的所有项目?

时间:2016-02-08 12:30:30

标签: javascript html knockout.js

我有以下对象:

var Transaction = function (data) {
    this.ID = ko.observable(data.transaction.ID);
    this.number = ko.observable(data.transaction.number);
    this.userID = ko.observable(data.transaction.userID);
    this.password = ko.observable(data.transaction.password);

    this.Properties = ko.observableArray(data.Property);
}

Properties observable数组看起来像这样(在JSON中):

[{"address1":"111 Broadway","city":"Brooklyn","state":"NY","zip":null},
{"address1":"222 Broadway","city":"Brooklyn","state":"NY","zip":null}]

在我的HTML中,我有类似的东西:

<span>PROPERTY</span>
<span data-bind="foreach: Properties">
<span data-bind="text: address1"></span>
<span data-bind="text: city"></span>
span data-bind="text: state"></span>
<span data-bind="text: zip"></span>
</span>

在浏览器中看起来像:

PROPERTY 
111 Broadway 
Brooklyn 
NY 
222 Broadway
Brooklyn 
NY

我希望它看起来像:

111 Broadway, Brooklyn, NY 
222 Broadway, Brooklyn, NY

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您应该将这些“foreached”属性包含在块级元素中,例如pdiv标记,例如像这样:

var Transaction = function (data) {
    this.ID = ko.observable(data.transaction.ID);
    this.number = ko.observable(data.transaction.number);
    this.userID = ko.observable(data.transaction.userID);
    this.password = ko.observable(data.transaction.password);
    this.Properties = ko.observableArray(data.properties);
};

var vm = new Transaction({ 
  transaction: { ID: 1, number: 2,  userID: 3, password: 'secret' },
  properties: [{"address1":"111 Broadway","city":"Brooklyn","state":"NY","zip":null},
               {"address1":"222 Broadway","city":"Brooklyn","state":"NY","zip":null}]
});

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<h1>
  <span data-bind="text: ID"></span> -
  <span data-bind="text: number"></span> -
  <span data-bind="text: userID"></span> -
  <span data-bind="text: password"></span>
</h1>
<span>PROPERTIES</span>
<!-- ko foreach: Properties -->
<p>
  <span data-bind="text: address1"></span>
  <span data-bind="text: city"></span>
  <span data-bind="text: state"></span>
  <span data-bind="text: zip"></span>
</p>
<!-- /ko -->

答案 1 :(得分:1)

您可以在Transaction原型中创建一个计算属性作为Properties 列表视图,这将简化与其关联的HTML标记。

this.propertyView = ko.pureComputed(function() {
  return this.Properties().map(function(prop) {
    var singleProp = '';
    for (var p in prop)
      if (prop[p])
        singleProp += prop[p] + ', ';
    return singleProp.slice(0,-2);
  });
}, this);
<span>PROPERTIES</span>
<!-- ko foreach: propertyView -->
<p data-bind="text: $data"></p>
<!-- /ko -->