将数组推入kb.collectionObservable

时间:2013-05-29 06:28:53

标签: jquery html5 backbone.js knockout.js

我想知道是否可以将数组推送到具有特定html功能的集合observable。例如,这就是我的HTML看起来像标准的方式:

  <thead class = "well">
    <th>Date</th>
    <th>Reference</th>
    <th>Note</th>
    <th><button data-bind= "click: add_note" class = "btn btn-mini"><i class="icon-plus"></i></button></th>   
  </thead>   
  <tbody data-bind = "foreach: policy_notes">
    <td data-bind = "dateTimeString: date_inserted"></td>
    <td data-bind = "text: reference"></td>
    <td data-bind = "text: note"></td>
    <td></td>   
  </tbody>

但我想推送一个<input>元素的新行。我正在推动这样一个新的行:

add_note: function(){
  page.viewModel.policy_notes.collection().push(
    {
      date_inserted: (new Date()).toISOString(),
      reference: 'HEY!',
      note: 'HEY!'
    }
  );
},

但我想参考和注意成为输入元素。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好的,这就是我解决它的方法,但它不是一个非常优雅的解决方案。我在这些行中添加了隐藏的输入框。

<tbody data-bind = "foreach: policy_notes">
    <td data-bind = "dateTimeString: date_inserted"></td>
    <td><span id = "ref_hide" data-bind = "text: reference"></span><input data-bind = "value: reference" type = "text" id = "ref_edit" style = "display:none; height: 10px" placeholder = "Reference"></input></td>
    <td><span id = "note_hide" data-bind = "text: note"></span><input data-bind = "value: note" type = "text" id = "note_edit" style = "display:none; height: 10px; width: 99%" placeholder = "Note"></input></td>
    <td><button data-bind = "click: save_note" id = "save_note" class = "btn btn-mini" style = "display:none"><i class="icon-ok"></i></button</td>
</tbody>

只需使用jquery show并隐藏。

add_note: function(element){
  page.viewModel.policy_notes.collection().unshift(
    {
      date_inserted: (new Date()).toISOString(),
      reference: '',
      note: ''
    },
  );

  $('#note_edit').show();
  $('#note_hide').hide();

  $('#ref_edit').show();
  $('#ref_hide').hide();

  $('#save_note').show();
},

使用jquery绑定是否有更优雅的解决方案?

相关问题