afterRender用于html绑定

sel*_*ary 7 javascript dom knockout.js

在Knockout将html添加到DOM并完成渲染后,有没有办法运行自定义代码?我需要这个,所以我可以绑定一个嵌套的视图模型来动态添加html代码.

就像是:

<div data-bind="html: dynamicHtml, afterRender: customCode"></div>

...

MyViewModel.prototype.customCode = function(){
    ko.applyBindings(self.MyInnerViewModel(), document.getElementById('someTagInTheDynamicHtml'));
};
Run Code Online (Sandbox Code Playgroud)

afterRender这里没有调用(仅适用于模板绑定?),自定义绑定也没有帮助,因为在update更新DOM后不保证调用" "事件.

And*_*ins 12

是的,仅afterRender适用于template绑定.

但是,您可以创建自定义绑定处理程序来跟踪html绑定更改,并在更新值时触发回调.我的例子:

ko.bindingHandlers.afterHtmlRender = {
    update: function(el, va, ab){
        ab().html && va()(ab().html);
    }
}
Run Code Online (Sandbox Code Playgroud)

缩短的参数名称:va - valueAccessor,ab - allBindings.

标记看起来应该是这样(绑定名称已更改):

<div data-bind="html: dynamicHtml, afterHtmlRender: customCode"></div>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/dDDjf/

更新

带有解释的简化绑定代码:

ko.bindingHandlers.afterHtmlRender = {
    update: function(element, valueAccessor, allBindings){
        // check if element has 'html' binding
        if (!allBindings().html) return;
        // get bound callback (don't care about context, it's ready-to-use ref to function)
        var callback = valueAccessor();
        // fire callback with new value of an observable bound via 'html' binding
        callback(allBindings().html);
    }
}
Run Code Online (Sandbox Code Playgroud)