Simple Knockout JS example not working

184 views
Skip to first unread message

Sandra Anderson

unread,
Dec 29, 2015, 11:34:24 PM12/29/15
to KnockoutJS
This is my first Knockout JS experience so sorry ahead of time for the simplicity....

I've copied a tutorial demo to try and get it to work in my .Net MVC 5 application but the data doesn't bind when I run the application.  I'm using Visual Studio Express 2013 and my code in my cshtml page is as follows:

@{
    ViewBag.Title = "TestKnockoutJS";
}
<script type='text/javascript' src='~/scripts/knockout-3.4.0.js'></script>

<h2>Test Knockout JS</h2>

<p>First name: <span data-bind="text: firstname"></span></p>

<script type='text/javascript' src='~/scripts/knockout-3.4.0.js'>


    var viewModel = {
        firstname: ko.observable("Bert")
    };

    ko.applyBindings(viewModel);

</script>

When the application is run, I see just the "First name:" label text and not "Bert".

Thanks in advance for any help.

Sandy 


Patrick Steele

unread,
Dec 30, 2015, 10:02:01 AM12/30/15
to knock...@googlegroups.com
1. Remove the "src" attribute from your second <script> tag.  I'm guessing that was just a copy/paste error from the earlier line.

2. Wrap your JS initialization code in the document.ready handler.  You could be trying to bind to elements that haven't been fully constructed in the DOM yet.  If you're using jQuery, do:

$(function() {
    // your code here
});

This email has been sent from a virus-free computer protected by Avast.
www.avast.com

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Sandra Anderson

unread,
Dec 30, 2015, 4:10:17 PM12/30/15
to KnockoutJS
Thanks heaps Patrick - I was able to fix the issue with your No.1 suggestion below.  Really appreciate your help - it's difficult to work out these small issues as a beginner to KnockoutJS.
Reply all
Reply to author
Forward
0 new messages