1

I am trying to convert some code from the knockout.js tutorial my visualstudio asp.net project.

I think I have everything set up just fine, I used bower to add the knockout library dependency.

I want to just get some code working to use knockout. Here is what I have:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>

        <p>First name: <strong data-bind="text: firstName"></strong></p>
        <p>Last name: <strong data-bind="text: lastName"></strong></p>
    <script src="lib/knockout/dist/knockout.js" type="text/javascript">
            function AppViewModel() {
                this.firstName = "Devin";
                this.lastName = "Salemi";
            }
            // Activates knockout.js
            ko.applyBindings(new AppViewModel());
    </script>
</body>
</html>

When I go to the site, all I see is First name:

Last name:

So the actual values aren't appearing, even though I set them in the JS. It should read - First name: Devin

Last name: Salemi

In the IDE, pretty sure all the functions are being linked to just fine, for example when I write ko. the IDE gives me all the options, so I think I have the library installed just fine...

Devin Andres Salemi
  • 2,198
  • 3
  • 12
  • 25

1 Answers1

1

You need to wrap your custom javascript in a separate <script> tag.

Whenever there's a src="" on script tag, it just ignores inside contents, and loads from a src file. Therefore you need another script tag without the src attribute for all custom scripts:

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js" type="text/javascript">
</script>
<script>
  function AppViewModel() {
    this.firstName = "Devin";
    this.lastName = "Salemi";
  }
  // Activates knockout.js
  ko.applyBindings(new AppViewModel());
</script>
GôTô
  • 7,974
  • 3
  • 32
  • 43
Ja9ad335h
  • 4,995
  • 2
  • 21
  • 29
  • Okay thank you, now it works no problem. Does it matter whether we put the script before versus after the html code that uses the script? Not sure what sort of process the browsers use to compile this stuff... – Devin Andres Salemi Feb 21 '17 at 22:47
  • its well explained [**here**](http://stackoverflow.com/questions/436411/where-should-i-put-script-tags-in-html-markup) – Ja9ad335h Feb 22 '17 at 14:03