javascript 用于 html 绑定的 afterRender

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16250594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:54:18  来源:igfitidea点击:

afterRender for html binding

javascriptdomknockout.js

提问by seldary

Is there a way to run custom code after Knockout has added the html to the DOM and finished rendering? I need this so I can bind a nested view model to dynamically added html code.

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

Something like:

就像是:

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

...

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

afterRenderis not called here (only works with template binding?), and a custom binding doesn't help either, because the "update" event is not guaranteed to be called after the DOM has been updated.

afterRender此处未调用(仅适用于模板绑定?),自定义绑定也无济于事,因为update在 DOM 更新后不能保证调用“ ”事件。

回答by Andrejs Kuzmins

Yes, afterRenderworks with templatebinding only.

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

But you can create custom binding handler that tracks htmlbinding changes and fires callback when value is updated. My example:

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

ko.bindingHandlers.afterHtmlRender = {
    update: function(el, va, ab){
        ab().html && va()(ab().html);
    }
}

Shortened param names: va - valueAccessor, ab - allBindings.

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

Also the markup should look like that (binding name is changed):

标记也应如下所示(绑定名称已更改):

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

http://jsfiddle.net/dDDjf/

http://jsfiddle.net/dDDjf/

Update

更新

Simplified binding code with explanations:

带解释的简化绑定代码:

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);
    }
}