【问题标题】:Knockout observableArray is not binding correctly淘汰 observableArray 未正确绑定
【发布时间】:2014-02-05 19:40:15
【问题描述】:

我正在学习knockout/json/mvc等,并尝试整理一个示例项目,但由于某种原因我无法正确绑定数据。

在下面的代码 sn-p 中,我从 Web 服务器获取一些 JSON 数据,然后尝试将其映射到函数,然后最终映射到我的淘汰赛 observableArray。然后我要做的是使用这个 observableArray 绑定到一个 HTML 表。然而,HTML 表不显示任何数据。我在 HTML 页面上放了一个标签,这个 确实 打印出来,但 toString() 值为: [Object object] 五次,与 JSON 数据中的属性数量相匹配。

谁能看出我遗漏了什么明显的东西?

从网络服务器收到的 JSON:

{ "Id": 1, "Name": "Inst123", "Price": 10, "DateTime": "2014-01-16T17:22:43.6383507+00:00", "Description": "Descriptions" };

.

视图模型

$(document).ready(function () {
    var gtViewModel = new GvTradeViewModel();
    ko.applyBindings(gtViewModel);
    console.log("ViewModel created");
});

    var GvTradeViewModel = function () {
    var self = this;
    self.gvTrades = ko.observableArray([]);

    var apiUrl = "http://localhost:57858/api/Trade/1";

    console.log("Starting JSON data retrieval from: " + apiUrl);

    $.getJSON(apiUrl)
       // Handle success event.
      .done(function (jsonData) {
          if (jsonData.isEmptyObject)
              console.log("NoData recieved");
          else {
              console.log("JSON data: " + jsonData);

              var mappedTrades = $.map(jsonData, function (gvTradeData) {
                  return new GvTrade(gvTradeData);
              });
              self.gvTrades(mappedTrades);
              console.log(self.gvTrades);

          }
      })
      // Handle error/fail event.
     .fail(function (jqxhr, textStatus, error) {
         var err = textStatus + ", " + error;
         console.log("Request Failed: " + err);
     });
};

function GvTrade(data) {
    this.TradeId = ko.observable(data.TradeId);
    this.InstrumentName = ko.observable(data.InstrumentName);
    this.DateTime = ko.observable(data.DateTime);
    this.Price = ko.observable(data.Price);
    this.Description = ko.observable(data.Description);
}

HTML

<table>
<thead>
    <tr>
        <th>TradeId</th>
        <th>InstrumentName</th>
        <th>Price</th>
        <th>DateTime</th>
        <th>Description</th>
    </tr>
</thead>
<tbody data-bind="foreach: $data.gvTrades">
    <tr>
        <td data-bind="text: InstrumentName"></td>
        <td data-bind="text: Price"></td>
        <td data-bind="text: DateTime"></td>
        <td data-bind="text: Description"></td>
    </tr>
</tbody>

【问题讨论】:

  • 不知道为什么你有$data。只需 foreach: gvTrades 即可。

标签: javascript jquery json knockout.js


【解决方案1】:

来自您服务器的 JSON 表示单个对象,而不是数组。

因此,当您调用 $.map 时,它不会正确地将您的数据映射为数组,因此您最终会得到一些不可用的对象。

要解决此问题,您需要确保您的 jsonData 在映射操作之前包含一个数组,您可以通过在其上调用 jQuery.makeArray 来做到这一点(或者您可以拥有一个基于您的数据的 if type 决定是否需要映射):

var mappedTrades = $.map($.makeArray(jsonData), function (gvTradeData) {
    return new GvTrade(gvTradeData);
});

演示JSFiddle.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2014-10-28
    相关资源
    最近更新 更多