简体   繁体   English

来自tockout.js视图模型的文本未显示在HTML中

[英]Text from knockout.js viewmodel not showing in html

I'm woking with MVC 4 playing around with Knockout for the front end architecture. 我很想MVC 4和Knockout一起玩前端架构。 I currently have the following script on my front end... 我目前在前端有以下脚本...

<script type="text/javascript" src="~/Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript" src="~/Scripts/knockout.mapping-latest.js"></script>

<script type="text/javascript">

    // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
    function AppViewModel() {
        this.merchantName = ko.observable("Store");
    }

    // Activates knockout.js
    ko.applyBindings(new AppViewModel());

</script>



<p>Merchant name: <strong data-bind="text: merchantName"></strong></p>

The problem is that the data for the merchantName attribute isn't showing in the HTML. 问题是商人名称属性的数据未在HTML中显示。 I run the same code on in the Knockout tutorial page http://learn.knockoutjs.com/#/?tutorial=intro and everything works fine. 我在Knockout教程页面http://learn.knockoutjs.com/#/?tutorial=intro上运行了相同的代码,并且一切正常。 What do you think could be the issue. 您认为可能是什么问题。 Also, I'm relatively new at front end development. 另外,我在前端开发方面还比较陌生。 What is the best way to debug knockout problems other than chrome debugger? 除chrome调试器外,调试敲除问题的最佳方法是什么?

Thanks! 谢谢!

You can use either of the below 2 for ko.applyBindings : 您可以为ko.applyBindings使用以下2种方法ko.applyBindings

  1. Add at the top of DOM with document.onload check 使用document.onload检查在DOM顶部添加
  2. At the bottom after DOM is loaded with out any check 在没有任何检查的情况下加载DOM之后的底部

From Documentation: http://knockoutjs.com/documentation/observables.html 从文档: http : //knockoutjs.com/documentation/observables.html

You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery’s $ function.

Use knockout.js only after your DOM is already loaded. 仅在您的DOM已加载后才使用kickout.js。 In your example just put 在你的例子中

<p>Merchant name: <strong data-bind="text: merchantName"></strong></p>

to the top of your file. 到文件顶部。

Also notice, that putting javascript right before </body> is closed is good practice in most cases 另请注意,在大多数情况下,将javascript放在</body>关闭之前是一种好习惯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM