0

Beginner.

Setting up KnockoutJS.com's first tutorial on my computer. The code works when the script is in the HTML document, but not when referring to it in a separate .js file. How to fix, with js code in a separate file?

Screenshot

Doesn't work:

//My JS file - C:/Users/XXXXXX/Desktop/ko/EX_HelloWorld_ViewModel.js:
function AppViewModel() {
    this.firstName = "Bert";
    this.lastName = "Bertington";
}
ko.applyBindings(new AppViewModel());
<!-- My HTML file:  -->
<script type='text/javascript' src='C:/Users/XXXXXX/Desktop/ko/knockout-3.5.1.js'></script>
<script type='text/javascript' src='C:/Users/XXXXXX/Desktop/ko/EX_HelloWorld_ViewModel.js'></script>

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

Works:

<!-- HTML file ONLY: -->
<script type='text/javascript' src='C:/Users/XXXXXX/Desktop/ko/knockout-3.5.1.js'></script>
<script type='text/javascript' src='C:/Users/XXXXXX/Desktop/ko/EX_HelloWorld_ViewModel.js'></script>

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<script>
    function AppViewModel() {
        this.firstName = "Bert";
        this.lastName = "Bertington";
    }
    ko.applyBindings(new AppViewModel());
</script>
SAL
  • 115
  • 6

1 Answers1

0

I realized this is the same root issue as this question.

So the solution is similar to Jason Spake's solution:

Solution 1: Move the second script line down - after the data-binds.

<!-- My HTML file:  -->
<script type='text/javascript' src='C:/Users/XXXXXX/Desktop/ko/knockout-3.5.1.js'></script>

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<script type='text/javascript' src='C:/Users/XXXXXX/Desktop/ko/EX_HelloWorld_ViewModel.js'></script>

Solution 2: Tie the applyBindings() to the event when document finishes loading.

//My JS file - C:/Users/XXXXXX/Desktop/ko/EX_HelloWorld_ViewModel.js:
function AppViewModel() {
    this.firstName = "Bert";
    this.lastName = "Bertington";
}
document.addEventListener("DOMContentLoaded", function(event) {
    ko.applyBindings(new AppViewModel());
})
SAL
  • 115
  • 6