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...
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.
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.
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>
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());
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With