【问题标题】:Knockout view model binding淘汰赛视图模型绑定
【发布时间】:2013-10-09 20:29:53
【问题描述】:

假设我有一张桌子:

<table>
 <tr class="expandable">
  <td><button>Expand</button></td>
  <td>Parent information #1</td>
  <td>Parent information #2</td>
 </tr>
 <tr class="expandable">
  <td><button>Expand</button></td>
  <td>Parent information #1</td>
  <td>Parent information #2</td>
 </tr>
</table>

我有一个淘汰赛模板:

<script type="text/html" id="child-template">
 <!-- ko foreach: children -->
  <tr>
   <td></td>
   <td>Child information #1</td>
   <td>Child information #2</td>
  </tr>
 <!-- /ko -->
</script>

还有一些 javascript

$('button').click(function() {
 $.getJSON(url, function(items) {
  var template = $('#child-template').html();
  $(this).closest('tr').after(template);
  var viewModel = { children: ko.observableArray(items) };
  ko.applyBindings(viewModel);
 });
});

我想要的是一个包含父行的表。如果我单击父行,我会通过 ajax 调用它的子行。当我得到孩子时,我想在父行下为每个孩子显示一个表格。

上述代码的问题是我将绑定应用于整个页面。我真正想要的是将该视图模型仅绑定到该父行。如果我首先单击父行 #1,它将显示正确的子行,但是当我单击父行 #2 时,两个子列表将包含相同的项目。

我在 JSFiddle 中可视化了我的问题:http://jsfiddle.net/6ehfb/1/

如果您首先单击父行#1 上的展开,它将显示子项#1。当您单击父行 #2 上的展开时,两个子列表都包含相同的项目。展开父行 #2 时,父行 #1 的子代不应受到影响。

如何解决?

【问题讨论】:

    标签: knockout.js knockout-2.0


    【解决方案1】:

    一个可能的解决方法是定义一个包含父集合的单一视图模型。这意味着每个父母都可以拥有自己独立的孩子数组。

    function generateParent(name, id)
    {
        function show() {
            this.expanded(true);
        }
    
        function initalDataCollection() {
            // Get data, add data to model
            // ...
    
            this.expanded(true);
            this.showAction(show);
        }
    
        return {
            expanded: ko.observable(false),
            information: ko.observable(name),
            children: ko.observableArray(),
            showAction: ko.observable(initalDataCollection)
        };
    }
    
    var viewModel = {
        parents: ko.observableArray()
    };
    
    //Add parent data to model
    // ...
    
    ko.applyBindings(viewModel);
    

    我提供了一个可行的解决方案,可以在http://jsfiddle.net/MatthewDunsdon/khMG8/找到

    HTML:

    <table border="1" data-bind="foreach: parents">
         <tr class="expandable">
            <td>
                <button data-bind="visible: !expanded(), click: showAction() ">Expand</button>
                <button data-bind="visible: expanded(), click: function() { expanded(false) }">Hide</button>
             </td>
            <td><span data-bind="text: information"></span></td>
         </tr>
        <!-- ko if: expanded -->
        <!-- ko foreach: children -->
        <tr>
            <td></td>
            <td data-bind="text: info"></td>
        </tr>
        <!-- /ko -->
        <!-- /ko -->
    
    </table>
    

    旁注:作为此解决方案的一部分,我让敲除处理 onClick 事件(“扩展”功能)并更新页面上的 html。

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 2014-01-18
      相关资源
      最近更新 更多