ko.applyBindings上是否有某种回调可用?
使用knockout.js 在我们当前的项目中,我们已经多次提到了这一点.
Using knockout.js on our current project, we came to this point several times already.
如何确保仅在页面上的所有绑定均已被Knockout应用后 才能执行某些Javascript代码?
How can I make sure some piece of Javascript code gets executed only after all bindings on the page have been applied by Knockout?
在我的特定用例中,我使用if
-bindings评估一些配置选项,并决定是否应渲染内部元素(在DOM中为=).只有在评估了这些if
绑定之后,我才需要计算某个元素内的DOM节点数.显然,如果我计算得太早,if
-绑定还没有删除那些不需要的DOM节点,那么计算就得出了错误的结果.
In my specific use case, I am using if
-bindings to evaluate some configuration options and decide whether the elements inside should be rendered (= in the DOM) or not. Only after these if
-bindings have been evaluated I need to count the number of DOM nodes inside a certain element. Obviously, if I count too early the if
-bindings have not removed those unwanted DOM nodes yet, so the counting comes to a wrong result.
可能会有所帮助.您可以使用模板绑定包装绑定(并将其他绑定放入模板),然后传递"afterRender"处理程序.呈现内容后,将调用此处理程序. 我已经美化了上面提到的jsfiddle(在评论中):
May be this will be helpful. You can wrap your binding with template binding (and put any another binding(s) inside the template) and pass the 'afterRender' handler. This handler will be called after content will have been rendered. I've beautified the jsfiddle mentioned above (in the comment):
var model = {
afterRenderCallback: function() {
// this method will be called after content rendered
var divContent = document.getElementById("textdiv").innerHTML;
alert(divContent);
},
txt: ko.observable("this text will be substituted in the div")
};
ko.applyBindings(model);
.content {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script type="text/html" id="wrappingTemplate">
<div id="textdiv" class="content" data-bind="text: txt"></div>
</script>
<!-- ko template: { name: 'wrappingTemplate', afterRender: afterRenderCallback } -->
<!-- /ko-->