我们是否应该在调用 ko.applyBindings 之前等待 DOM 加载 [英] Should we wait for DOM to load before calling ko.applyBindings
问题描述
根据标题,调用ko.applyBindings
之前需要等待DOM加载还是Knockout会自动处理?
As per the title, is it necessary to wait for the DOM to load before calling ko.applyBindings
or will Knockout handle this automatically?
即 - 我可以安全地这样做:
I.e - am I safe to just do:
<script>
(function() {
var model = new my.Model();
ko.applyBindings(model);
})();
</script>
推荐答案
没有 KO 不会自动处理这个(所以自调用函数只会在你的页面底部工作),你必须等待 DOM 加载ko.applyBindings
调用.
No KO doesn't handle this automatically (so the self invoking function would work only at the bottom your page), you have to wait for the DOM loaded with the ko.applyBindings
call.
来自文档:
要激活 Knockout,请将以下行添加到 块:
To activate Knockout, add the following line to a
<script>
block:
ko.applyBindings(myViewModel);
您可以将脚本块放在HTML 文档的底部,或者您可以将其放在顶部和将内容包装在 DOM 就绪处理程序中,例如 jQuery 的 $ 函数.
这篇关于我们是否应该在调用 ko.applyBindings 之前等待 DOM 加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!