2013-10-09 107 views
1

可以说我有一个表:淘汰赛视图模型结合

<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上单击展开时,两个子列表都包含相同的项目。父级行#1的子级在扩展父级行#2时不应受到影响。

如何解决?

回答

3

可能的修复方法是定义包含父代集合的单个视图模型。这意味着每个家长都可以拥有独立的儿童数组。

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。