JWP
JWP

Reputation: 6963

Knockout newbie, can anyone spot why this doesn't work

I created a MVC 4.0 project to test Knockout, the mark up is shown below (BTW I loaded all the latest stuff from NUGET) What is shown below is the client side source after the rendering of the View from MVC. I've looked at the network side and saw all the links and scripts arrive at the client. Browser is Chrome. The console doesn't show any errors. Finally, the myMessage text is never rendered. If I put breakpoints in the JS, I do see that the Knockout library is called... Just wondering what I'm doing wrong here.

  <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="/Scripts/jquery-2.1.1.js"></script>
        <script src="/Scripts/jquery.validate.js"></script>
        <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
        <script src="/Scripts/knockout-3.2.0.js"></script>

        <link href="/Content/site.css" rel="stylesheet" />

        <script src="/Scripts/modernizr-2.6.2.js"></script>
    </head>
    <body>

        <h2>Index</h2>
        Today's message is: <span data-bind="text: myMessage"></span>

        <script type="text/javascript">
            var viewModel = {
                myMessage: ko.observable() // Initially blank
            };
            viewModel.myMessage("Hello, world!"); // Text appears
        </script>
    </body>
    </html>

Upvotes: 0

Views: 49

Answers (2)

super cool
super cool

Reputation: 6045

well you missed the most important part in knockout 'applyBindings' .

Once you construct your view model you just need to call

Step 1: Starting point

 ko.applyBindings(viewModel) 

step 2: next view model executes

var viewModel = {
                myMessage: ko.observable() 
            };

Refer knockout documentation http://knockoutjs.com/documentation/introduction.html

Sample fiddle to test your scenario Here

Upvotes: 1

you need to call ko.applyBindings. try this:

<script type="text/javascript">
            var viewModel = {
                myMessage: ko.observable() // Initially blank
            };
            ko.applyBindings(viewModel) // you need to initialize ko :)
            viewModel.myMessage("Hello, world!"); // Text appears
</script>

Upvotes: 3

Related Questions