Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a "Cannot read property 'nodeType' of null" error with Knockout JS?

Today is the first day for me in Knockout . Got struck with it . Below is my first sample code using knockout.js and it shows an error .

Cannot read property 'nodeType' of null

Here is my script:`

   function ViewModel()  
   {  
     var self = this;  
     self.n1 = ko.observable(10);  
     self.n2 = ko.observable(10);  
     self.n3 = ko.observable(10);  
   }  
   ko.applyBindings(new ViewModel());  `

Here is my html:

<body>
<p>Number1:<input data-bind="value:n1"></input></p>
<p>Number2:<input data-bind="value:n2"></input></p>
<p>Number3:<input data-bind="value:n3"></input></p>
</body>

I want to know the reason for the above error and how to overcome it...

like image 267
Prasath K Avatar asked Feb 26 '13 13:02

Prasath K


People also ask

Can not read properties of null JS?

The "Cannot read property 'click' of null" error occurs when trying to call the click method on a null value. To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.

What does Cannot read property style of null mean?

The "Cannot read property 'style' of null" error occurs when: trying to access the style property on a null value, e.g. after calling getElementById with an invalid identifier. inserting the JS script tag before the DOM elements have been declared.


3 Answers

If you set up your code like this, it'll work.

<body>
<p>Number1:<input data-bind="value:n1"></p>
<p>Number2:<input data-bind="value:n2"></p>
<p>Number3:<input data-bind="value:n3"></p>
<script src="knockout.js"></script>
<script>

function ViewModel() {  
   var self = this;  
   self.n1 = ko.observable(10);  
   self.n2 = ko.observable(10);  
   self.n3 = ko.observable(10);
}  

ko.applyBindings(new ViewModel());  `

</script>
</body>
like image 151
Brigand Avatar answered Oct 03 '22 11:10

Brigand


If you want to keep your <script> at the top of the page, you can use jQuery's ready() function to delay the initialization until the page has loaded.

$(document).ready(function() {
    ko.applyBindings(new ViewModel());
});
like image 36
lance-java Avatar answered Oct 03 '22 10:10

lance-java


I think ko.applyBindings(obj); should be write under view model.

<!DOCTYPE html>
<html>
<head>
    <title>KO Examples</title>
    <script type='text/javascript' src='knockout-3.1.0.js'></script>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript'>
        var  obj = {
            first_name : 'Gazal Irish'
        };


    </script>

</head>
<body>
<div>
    <p>My name : <span data-bind="text: first_name"></span>
<p> 
</div>
<script type="text/javascript">

    ko.applyBindings(obj);
</script>

</body>
</html>
like image 36
Shemeer M Ali Avatar answered Oct 03 '22 12:10

Shemeer M Ali