Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get knockout running

I'm a complete noob in knockoutjs and I'm facing a problem just from the beginning. I have done everything described in the installation guide, but I can't get it working.

My HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
   <HEAD>
      <script type='text/javascript' src='js/knockout-3.0.0.js'></script>
      <script type='text/javascript' src='js/myTasks.js'></script>
      <TITLE>Your Tasks</TITLE>
   </HEAD>
   <BODY>
     <p>First name: <strong data-bind="text: firstName"></strong></p>
     <p>Last name: <strong data-bind="text: lastName"></strong></p>
   </BODY>
</HTML>

My viewmodel - contained in the myTasks.js file:

function AppViewModel() {
    this.firstName = "Bert";
    this.lastName = "Bertington";
}
ko.applyBindings(new AppViewModel());

What I'm getting is:

First name:

Last name: 

The above code is the code used in the first knockoutjs tutorial.

Why I can't run it? I know that I'm missin something really small, but I'm not able to spot it.

like image 592
chility Avatar asked Nov 23 '13 10:11

chility


Video Answer


2 Answers

Wrap you knockout code in $( document ).ready( function() {} );

$( document ).ready( function() {
    function AppViewModel() {
        this.firstName = "Bert";
        this.lastName = "Bertington";
    }
    ko.applyBindings(new AppViewModel());
} );

And don't forget to include jquery itself.

like image 115
u_mulder Avatar answered Oct 22 '22 15:10

u_mulder


I know this question was answered a long time ago, but it is one of the top searches on Google when searching for solutions on this issue. You should not have to use JQuery with knockout.js as is implied by the accepted answer. A better solution would be to just move your script tag referencing myTask.js to the bottom of your body:

<BODY>
 <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='js/myTasks.js'></script>
</BODY>

This should allow your viewmodel code to work without having to include jQuery.

like image 36
Mike Avatar answered Oct 22 '22 14:10

Mike