Knockout.js 如何向数据绑定添加afterRender=";与:

Knockout.js 如何向数据绑定添加afterRender=";与:,knockout.js,Knockout.js,我需要将afterRender回调添加到现有的数据绑定语句中,但我在语法方面遇到了困难 以下是我需要将afterRender添加到的代码,该代码当前可以正确渲染: <div data-bind="with: detail"> <div class="row"> <div class="header"> <span data-bind="html: headerMainSegm

我需要将afterRender回调添加到现有的数据绑定语句中,但我在语法方面遇到了困难

以下是我需要将afterRender添加到的代码,该代码当前可以正确渲染:

    <div data-bind="with: detail">
        <div class="row">
            <div class="header">
                <span data-bind="html: headerMainSegment"></span>
                <span data-bind="text: headerSecondSegment"></span>
                <div data-bind="text: rollupSegment"></div>
            </div>
        </div>
    </div>

以下是我尝试过的,但内容消失了:

    <div data-bind="with: { data: detail, afterRender: customCode }">
        <div class="row">
            <div class="header">
                <span data-bind="html: data.headerMainSegment"></span>
                <span data-bind="text: data.headerSecondSegment"></span>
                <div data-bind="text: data.rollupSegment"></div>
            </div>
        </div>
    </div>


我将customCode方法添加到viewmodel中,但渲染时所有数据属性都显示为null

如果要使用
afterRender
,则需要使用
模板
绑定

<div data-bind="template: { data: detail, afterRender: customCode }">
   <div class="row">
        <div class="header">
            <span data-bind="html: headerMainSegment"></span>
            <span data-bind="text: headerSecondSegment"></span>
            <div data-bind="text: rollupSegment"></div>
        </div>
    </div>
</div>
自定义绑定如下所示:

ko.bindingHandlers.customCode = {
    update: function (element, valueAccessor, allBindings, vm, context) {
        ko.unwrap(valueAccessor());     // access the value so we're updated when it changes

        // do my custom code with the element... 
    }
};

您是否尝试了
data bind=“with:{data:detail},afterRender:customCode”
?我得到了相同的结果,空白span标记。我在文档中没有看到任何迹象表明,对于
with
绑定,敲除支持
afterRender
。只需
模板
foreach
<代码>with没有两种形式(如
foreach
)来处理其他参数。如果您在成员前面加上
数据
,它需要有美元符号(
$data
),谢谢。添加到BindingHandler的是我最终使用的解决方案。由于第一个解决方案有问题,get$parent中的绑定未定义。
ko.bindingHandlers.customCode = {
    update: function (element, valueAccessor, allBindings, vm, context) {
        ko.unwrap(valueAccessor());     // access the value so we're updated when it changes

        // do my custom code with the element... 
    }
};