user3306826
user3306826

Reputation: 3

knockout script not working

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="/Content/site.css" rel="stylesheet"/>

    <script src="/Scripts/modernizr-2.6.2.js"></script>
<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/knockout-2.2.0.debug.js"></script>


</head>
<body>


<h2>Index</h2>






    <script type="text/javascript">
        // This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
        function AppViewModel() {
            this.firstName = "Bert";
            this.lastName = "Bertington";
        }

        // Activates knockout.js
        ko.applyBindings(new AppViewModel());
    </script>
    <p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
</body>
</html>

The above code does not return the firstname and lastname i selected. I tried changing with knockout knockout-2.2.0.js but wouldn't work. What am i doing wrong?

Upvotes: 0

Views: 307

Answers (1)

Robert Westerlund
Robert Westerlund

Reputation: 4838

The reason it isn't working is that you're asking knockout to apply bindings before the DOM elements which you want to bind to have been loaded, so when knockout traverses the DOM looking to data-bind it won't find your p elements (they haven't been loaded yet, since they are placed after the script tag).

Either move the script tag to the end of the body, or ensure that your code isn't run until the DOM has finished loading by running the code which calls ko.applyBindings in the DOMContentLoaded event.

Upvotes: 3

Related Questions