user1795804
user1795804

Reputation:

Text from knockout.js viewmodel not showing in html

I'm woking with MVC 4 playing around with Knockout for the front end architecture. 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. I run the same code on in the Knockout tutorial page http://learn.knockoutjs.com/#/?tutorial=intro and everything works fine. 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?

Thanks!

Upvotes: 1

Views: 177

Answers (2)

Aditya Singh
Aditya Singh

Reputation: 16660

You can use either of the below 2 for ko.applyBindings:

  1. Add at the top of DOM with document.onload check
  2. At the bottom after DOM is loaded with out any check

From Documentation: 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.

Upvotes: 1

Boris Zagoruiko
Boris Zagoruiko

Reputation: 13174

Use knockout.js only after your DOM is already loaded. 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

Upvotes: 0

Related Questions