1

I am fairly new to knockout js and the documentation maintained on official site does not provide complete html file. So I ended up writing my own script tags. When I created the html markups it did not work as expected. However just altering the position of script tags makes it work.

My question is, when the script tag is placed up top, then the function is made available before it is called in the html body elements.Still it does not data bind, whereas placing the script at bottom just solves it. How is this possible by just reordering the position of script tag? Can someone provide the order in which things must be made available. I understand that many people prefer having script towards the end so that the DOM is completely ready and for speed considerations.

My code below:

  1. Does not data bind.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
<script type="text/javascript">
var myViewModel = {personName:'Bob', personAge:31};
ko.applyBindings(myViewModel);
</script>

The name is <span data-bind="text: personName"></span>

</body>
</html>
  1. Works

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
</head>
<body>
The name is <span data-bind="text: personName"></span>
<script type="text/javascript">
var myViewModel = {personName:'Bob', personAge:31};
ko.applyBindings(myViewModel);
</script>

</body>
</html>
Abhi7950
  • 138
  • 1
  • 7

1 Answers1

5

When ko.applyBindings gets called knockout searches the document for any data-bind tags and applies the appropriate bindings. Therefore, the document and any data-bind tags must already be loaded before ko.applyBindings is called or knockout will not find anything to bind to.

You have a couple of options that work:

  1. Move applyBindings to the bottom of the document where any data-binds are already in place by the time it gets called.
  2. Wrap applyBindings in a callback function so that it can be defined anywhere, but will wait to execute until the document has finished loading. For this you can use jQuery's $(document).ready(), or if you don't have jQuery see this SO question for other equivalent options
Jason Spake
  • 4,224
  • 2
  • 14
  • 22