KnockOut js脚本标记不应用数据绑定 [英] KnockOut js script tag does not apply data binding

查看:44
本文介绍了KnockOut js脚本标记不应用数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对淘汰js相当陌生,并且官方网站上维护的文档没有提供完整的html文件.因此,我最终编写了自己的脚本标签.当我创建html标记时,它没有按预期工作.但是,只需更改脚本标签的位置即可使其工作.

I am fairly new to knockout js and the documentation maintained on official site does not provide complete html file. So I ended up writing my own script tags. When I created the html markups it did not work as expected. However just altering the position of script tags makes it work.

我的问题是,当将script标记放在顶部时,然后在html body元素中调用该函数之前,该函数才可用.仍然没有数据绑定,而将脚本放在底部只是解决了问题.仅通过重新排序脚本标签的位置怎么可能?有人可以提供必须使事物可用的顺序.我了解到,很多人都喜欢在最后使用脚本,以便DOM完全准备就绪并出于速度考虑.

My question is, when the script tag is placed up top, then the function is made available before it is called in the html body elements.Still it does not data bind, whereas placing the script at bottom just solves it. How is this possible by just reordering the position of script tag? Can someone provide the order in which things must be made available. I understand that many people prefer having script towards the end so that the DOM is completely ready and for speed considerations.

我的下面的代码:

  1. 不绑定数据.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
<script type="text/javascript">
var myViewModel = {personName:'Bob', personAge:31};
ko.applyBindings(myViewModel);
</script>

The name is <span data-bind="text: personName"></span>

</body>
</html>

  1. 作品

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
The name is <span data-bind="text: personName"></span>
<script type="text/javascript">
var myViewModel = {personName:'Bob', personAge:31};
ko.applyBindings(myViewModel);
</script>

</body>
</html>

推荐答案

调用ko.applyBindings时,敲除会在文档中搜索任何数据绑定标签并应用适当的绑定.因此,在调用ko.applyBindings之前,文档和所有数据绑定标签必须已经加载,否则敲除将找不到要绑定的内容.

When ko.applyBindings gets called knockout searches the document for any data-bind tags and applies the appropriate bindings. Therefore, the document and any data-bind tags must already be loaded before ko.applyBindings is called or knockout will not find anything to bind to.

您有几个可行的选择:

  1. 将applyBindings移至文档底部,直到调用它时任何数据绑定都已就绪.
  2. 在回调函数中包装applyBindings,以便可以在任何地方定义它,但是将等待执行直到文档完成加载.为此,您可以使用jQuery的$(document).ready(),或者如果您没有jQuery,请参阅此 SO问题用于其他等效选项
  1. Move applyBindings to the bottom of the document where any data-binds are already in place by the time it gets called.
  2. Wrap applyBindings in a callback function so that it can be defined anywhere, but will wait to execute until the document has finished loading. For this you can use jQuery's $(document).ready(), or if you don't have jQuery see this SO question for other equivalent options

这篇关于KnockOut js脚本标记不应用数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆