淘汰赛得到了工作

时间:2014-03-24 23:14:10

标签: knockout.js foreach

我的这个对象包含3个音符

{
 notes:[
 {
   id:{type:"integer",value:"215356161"},
   body:"", 
   author_id:"980766",
   subject_id:"201674760",
   created_at:{date:"2014-03-24 16:50:14",timezone_type:2,timezone:"Z"},
   attachments:{
         type:"array",
         attachments:[{
             id:{type:"integer",value:"77791298"},
             url:"https://fdgsgds.highrisehq.com/files/777915446298",
             name:"nav-rubik-03.mp3",
             size:"13954"
       ]} //typo
   }
 },
 {
   id:{type:"integer",value:"215356129"},
   body:"Test",author_id:"980766",
   subject_id:"201674760",
   created_at:{date:"2014-03-24 16:50:08",timezone_type:2,timezone:"Z"}
 },
 {

 ...
 }]
}

我想迭代它

第二个foreach无效

<div data-bind="foreach: appModel.issue().highriseNotes()">
    <p data-bind="text:$data.created_at.date"></p>

    <p data-bind="text:$data.body"></p>
    <!-- UPDATE, The Solution was to check if there were attachments at all -->
    <!-- ko if:$data.attachments -->
   <div data-bind="foreach: $data.attachments.attachments)">
       <p data-bind="text:$data">   </p>                                                        
   </div>
    <!-- /ko -->
</div>

导致

Uncaught TypeError: Unable to process binding 
"text: function (){return $data.attachments.attachments }"
Message: Cannot read property 'attachments' of undefined 

如何迭代“附件”中的“附件”

2 个答案:

答案 0 :(得分:1)

在以下示例中,我将notes数组传递给ko.observableArray

解决方案:http://jsfiddle.net/Wb84f/1/

答案 1 :(得分:1)

数组中的一个元素缺少附件属性,导致您遇到绑定失败。

一些解决方案。

1。将内部foreach包裹在if绑定中

<!-- ko if:$data.attachments -->
  <div data-bind="foreach..." />
<!-- /ko -->

2。确保每个notes元素中始终具有附件属性。这可能需要更改您的JSON提供程序或序列化程序,或者只是确保您的附件属性服务器端是空数组或列表,具体取决于您的技术堆栈。

{
  notes:[
  {
     ...
     attachments: {
       type:"array",
       attachments:[]           
     }
  }
}

3。将绑定更改为默认为空对象。

<div data-bind="foreach: ($data.attachments || {}).attachments)">