Book Image

Knockout.JS Essentials

Book Image

Knockout.JS Essentials

Overview of this book

Table of Contents (16 chapters)
KnockoutJS Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Using resources in the view-model


Now that we have created our product resource, we will use it in our view-model to get our data back by following these steps:

  1. First of all, link the ProductResource.js file in the index.html file, as follows:

    <script type='text/javascript' src='js/resources/ProductResource.js'></script>

    Since the resource works asynchronously, you can't apply bindings at the end of the file because the data may not be ready yet. Therefore, bindings should be applied when the data has arrived.

    To do this, create a method called activate. This method will be fired at the end of the file, on the same line we called ko.applyBindings earlier, in the following manner:

    1. Take this line of code:

      ko.applyBindings(vm);
    2. Replace it with this one:

      vm.activate();
  2. Now define the activate method in the view-model:

    var activate = function () {
      ProductResource.all().done(allCallbackSuccess);
    };

    When you call the all method a jQuery promise is returned. To manage the results of the promise...