Knockout的renderTemplate不绑定$ root

时间:2013-10-12 18:51:25

标签: knockout.js

我正在尝试创建一个表,利用Knockout,我可以在其中选择一个,在所选行下面插入一些功能,做一些事情,并能够删除插入的行。我实际上可以让行插入正常工作,但是失去了绑定到循环项的父级的功能。

HTML看起来像这样:

<table data-bind="visible: currentRecord() === null">
    <thead>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Affiliation</th>
            <th></th>
        </tr>
    </thead>
    <tbody data-bind="template: {name: 'row-template', foreach: records}">

    </tbody>
</table>

我使用两个模板(一个用于单行,一个用于包含单行的行)

<script id="row-template" type="text/html">
    <tr class="actual-row">
        <td class="ui-icon ui-icon-circle-arrow-e" data-bind="insertRow: {
            templateName: 'custom-template', 
            rowIdentifier: 'extra-content', 
            singleRowTemplate: 'row-template',
            data: $data}">
                <input type="hidden" data-bind="value: Id" />
        </td>
        <td data-bind="text: Name"></td>
        <td data-bind="text: Affiliation"></td>
        <td><a href="#" data-bind="click: $root.clickMe">Click Me!</a>
    </tr>
</script>

<script id="custom-template" type="text/html">
    <!-- ko template: { name: 'row-template' } -->
    <!-- /ko -->
<tr id="extra-content">
    <td colspan="4" > 
        <div>You have: <input type="number" data-bind="value: currentAmount,     valueUpdate: 'keypress'" /> </div>
        <div>You need <strong data-bind="text: Max - currentAmount()" > </strong> more</div > 
    </td>
</tr>
</script>

在创建过程中,绑定非常完美。我可以点击 Click Me!锚点就好了。但是,当我执行代码以插入行时,它会运行一个调用

的自定义绑定处理程序
ko.renderTemplate(value.templateName, value.data, {}, cell.parent(), "replaceNode");

其中

  • value是传递给insertRow bindingHandler
  • 的JS对象
  • cell是点击插入/删除特殊行的TD元素的jQuery对象。

我怀疑个人记录与其父记录之间的关系已经丢失,我不知道如何利用它。任何人都可以帮助我吗?

我有一个小提琴,我一直在玩here.

1 个答案:

答案 0 :(得分:0)

您的任务可以通过更简单的方式解决。您甚至不需要编写如此复杂的自定义绑定,因为每个超级英雄的可扩展行都是相同的。

为每个超级英雄添加2行,但只能使一行不可见:

<tbody data-bind="foreach: records">
    <tr class="actual-row">
        <td class="ui-icon ui-icon-circle-arrow-e" 
        data-bind="click: expanded.toggle">
            <input type="hidden" data-bind="value: Id" />
        </td>
        <td data-bind="text: Name"></td>
        <td data-bind="text: Affiliation"></td>
        <td><a href="#" data-bind="click: $root.clickMe">Click Me!</a>

        </td>
    </tr>
    <tr id="extra-content" data-bind="visible: expanded">
        <td colspan="4">
            <div>You have:
                <input type="number" data - bind="value: currentAmount, valueUpdate: 'keypress'" />
            </div>
            <div>You need <strong data-bind="text: Max - currentAmount()"></strong > more </div> 
</td> </tr>

</tbody>

visible绑定到行数据中的某个可观察值:

ko.utils.arrayForEach(self.records(), function(rec){
    rec.expanded = ko.observable(false);
    rec.expanded.toggle = function(){
        rec.expanded(!rec.expanded());
    };
});

这样你就可以开始工作:http://jsfiddle.net/sQvUK/6/

P.S。唯一没有撤消的是箭头图标的类切换器。