Note that there are some explanatory texts on larger screens.

plurals
  1. POShould data load occur in model or viewmodel when using Knockout
    primarykey
    data
    text
    <p>Is it wise to put your ajax calls in your Knockout ViewModel or should it instead be placed in a Model? I've come up with a few approaches but none feel completely right. </p> <p><strong>Approach 1 - ViewModel Only</strong></p> <pre><code>window.someDataVM = function() { var self = this; //used to enable loading indicator self.pendingLoad = ko.observable(true); self.myData = ko.observableArray(); self.load = function() { //make ajax call and populate myData observable array } } </code></pre> <p><em>Advantages</em></p> <ul> <li>Simplest code structure - easier to maintain</li> </ul> <p><em>Disadvantages</em></p> <ul> <li>No reuse for data retrieval</li> </ul> <p><strong>Approach 2 - Model and ViewModel With Callback</strong></p> <pre><code> window.someDataVM = function() { var self = this; //used to enable loading indicator self.pendingLoad = ko.observable(true); self.myData = ko.observableArray(); self.load = function() { someDataM.load(function(data) { //populate myData observable array }); } } window.someDataM = function() { return { load: function(callback) { //get data via ajax and return via callback } } } </code></pre> <p><em>Advantages</em></p> <ul> <li><p>More code reuse on data retrieval (i.e. one place to load someData)</p></li> <li><p>Simpler interface that approach 3</p></li> </ul> <p><em>Disadvantages</em></p> <ul> <li>Uses callbacks</li> </ul> <p><strong>Approach 3 - Model and ViewModel With Knockout Model</strong></p> <pre><code>window.someDataVM = function() { var self = this; //used to enable loading indicator self.pendingLoad = ko.observable(true); self.myData = ko.observableArray(); self.load = function() { someDataM.load(); } someDataM.isLoaded.subscribe(function(isLoaded) { if (isLoaded) { //populate observable array } }); } window.someDataM = function() { return { isLoaded: ko.observable(false); items: [], load: function() { //get some data, populate items, set isLoaded } } }(); </code></pre> <p><em>Advantages</em></p> <ul> <li>Doesn't use callback</li> <li>Keeps data code centralized</li> </ul> <p><em>Disadvantages</em></p> <ul> <li>Will be complicated to have lots of data entry points (i.e. LoadById, LoadByName, etc, etc.)</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload