Jacques Ramsden Jacques Ramsden - 24 days ago 7
HTML Question

Using a external .js file with knockout not applying bindings

I am trying to get to grips with Knockout and so I have created the following html file...

<html>
<head>
<script type='text/javascript' src='http://knockoutjs.com/downloads/knockout-3.2.0.js'></script>
<script type='text/javascript' src='jsfile.js'></script>
</head>
<h1>Welcome<h1>

<button data-bind="click: speak">Say it</button>

<script>
alert('Binding Started');

function indexViewModel() {

this.speak = function() {
alert('Working!!');
};
}

ko.applyBindings(new indexViewModel());

alert('Binding Done');


</script>

</html>


When I load the page all is well in the land of milk and honey. I get an alert that says the binding is starting.... Then I get another alert saying that its done and when I click the button... Yip you guessed it I get an alert stating that its working.

The problem I am having is when I try to separate the java-script code out into an external file it does not apply the bindings.

So my html file will look like this......

<html>
<head>
<script type='text/javascript' src='http://knockoutjs.com/downloads/knockout-3.2.0.js'></script>
<script type='text/javascript' src='jsfile.js'></script>
</head>
<h1>Welcome<h1>

<button data-bind="click: speak">Say it</button>

</html>


And my file "jsfile.js" looks like this....

alert('Binding Started');

function indexViewModel() {

this.speak = function() {
alert('Working asstastic');
};
}

ko.applyBindings(new indexViewModel());


alert('Binding Done');

When I now load the html page I get an alert for the binding starting and then ... Nothing...... :(

If I remove the line for the ko.applyBindings(.. then it gives me the second alert that the binding is done. however obviously the button does noting.

What am I doing wrong It seems like its not seeing the knockout functions in the .js file but I have hit a brick wall..

Please help..

Answer

The 'head' html tags will get loaded before the 'body' tags...

Your applying knockout bindings in your 'head' tags. ( in your custom .js file after including knockout )

These bindings / Javascript code is loaded / executed / happening before the body has been loaded; Thus its / knockout is trying to bind js data to html body UI content which the browser / window does not yet know about.

p.s. - Put your content in a 'body' after the 'head'. Then include your custom .js file after the 'body,' this way everything is now loaded in order to achieve what you want. Alternatively... Include logic in the .js itself to execute after DOM / window has finished loading.