【问题标题】:KnockoutJS - How to compute data from returned JSON resultsKnockoutJS - 如何从返回的 JSON 结果中计算数据
【发布时间】:2017-11-30 22:54:03
【问题描述】:

我正在尝试从返回的 JSON 中更改 DOB resource.birthDate 的显示方式

Knockout.js:

this.rows= ko.observableArray([]);

$.getJSON(
  "./malib/api-call.php",
  function (data) {
     self.rows(data.entry);
  }
);

和 HTML:

           <tbody data-bind="foreach: rows">
            <tr data-bind="attr: { id: resource.id}, css: {'isSelected':$root.selPatient() == $data}, click: $parent.highlightPatient.bind($parent), event : { dblclick: $parent.selectPatient.bind($parent) }" >
                <td class="col_name" data-bind="text: resource.name[0].text"></td>
                <td class="col_dob" data-bind="text: resource.birthDate"></td>
                <td class="col_gender" data-bind="text: resource.gender"></td>
                <td class="col_address" data-bind="text: resource.address[0].line[0] + ', ' + resource.address[0].city + ' ' + resource.address[0].state + ' ' + resource.address[0].postalCode"></td>
            </tr>
        </tbody>

我已将以下代码添加到 KnockoutJS 部分:

this.rows= ko.observableArray([]);

$.getJSON(
  "./malib/api-call.php",
  function (data) {
     self.rows(data.entry);

                        self.returnDOB = function(item) {

                            var nonusDOB = item.split("-");
                            return nonusDOB[2] +"/"+ nonusDOB[1] +"/"+ nonusDOB[0];
                        };  
  }
);

并替换为 HTML:

<td class="col_dob" data-bind="text: returnDOB(resource.birthDate)"></td>

但该解决方案会引发错误

Message: returnDOB is not defined

有什么建议吗?

【问题讨论】:

    标签: json knockout.js getjson


    【解决方案1】:

    绑定试图在函数存在之前执行你的函数。您应该在 json 请求之外创建函数。

    self.returnDOB = function(item) {
        var nonusDOB = item.split("-");
        return nonusDOB[2] +"/"+ nonusDOB[1] +"/"+ nonusDOB[0];
    }; 
    
    $.getJSON(
      "./malib/api-call.php",
      function (data) {
        self.rows(data.entry); 
      }
    );
    

    【讨论】:

    • 还是同样的错误Unable to process binding "text: function (){return returnDOB(resource.birthDate) }" Message: returnDOB is not defined
    • @JackTheKnife 没有看到你所有的代码我只能猜测结构,但由于你的绑定在 foreach 循环中,它可能需要看起来像data-bind="text: $parent.returnDOB(birthDate())"
    • $parent.returnDOB(resource.birthDate) 完成了这项工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2016-09-15
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    相关资源
    最近更新 更多