Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we wait for DOM to load before calling ko.applyBindings

Tags:

knockout.js

As per the title, is it necessary to wait for the DOM to load before calling ko.applyBindings or will Knockout handle this automatically?

I.e - am I safe to just do:

<script>
(function() {

    var model = new my.Model();
    ko.applyBindings(model);

})();
</script>
like image 248
Ben Foster Avatar asked Feb 06 '13 19:02

Ben Foster


1 Answers

No KO doesn't handle this automatically (so the self invoking function would work only at the bottom your page), you have to wait for the DOM loaded with the ko.applyBindings call.

From the documentation:

To activate Knockout, add the following line to a <script> block:

ko.applyBindings(myViewModel);

You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery’s $ function.

like image 173
nemesv Avatar answered Nov 08 '22 03:11

nemesv