Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Creating a Deferred object to return to a view

$
0
0
I've been trying to integrate the LocalStorage model from TodoMVC into the existing models in my project and I'm so close, yet can't figure out how to return the right object from my findAll such that the view can use it to create the document fragment.

In the following code, when there's no data in the local store, it follows the ajax call and the view renders correctly with the data. The JSON from that fetch is stored in local storage under 'foo-canjs'. On the next page load, the findAll from FooLocal gets the JSON from local storage and I think I need to return a Deferred object back to my view. So I create a Deferred object similar to how it's done in the LocalStorage model in TodoMVC. However, when my view renders, there's no data. The 'data' var that I put in the Deferred object's resolve method contains the correct information. So the JSON is there, I just need to create the "right" kind of Deferred object for my view to slurp.

Any ideas what I'm missing? Thanks in advance for any guidance!


  1.     var Foo = can.Model ({
  2.         findAll: function(params) {
  3.             var returnVal;
  4.             FooLocal.findAll({}, function(data) {
  5.                 if (!data || data.total_count == 0) {

  6.                     returnVal = can.ajax({
  7.                         url: '/endpoint,
  8.                         type: 'get',
  9.                         success: function(data) {
  10.                             new FooLocal(data).save();
  11.                         }
  12.                     });
  13.                 } else {
  14.                     var def = new can.Deferred;
  15.                     def.resolve(data);
  16.                     returnVal = def;
  17.                 }
  18.             });
  19.             return returnVal;
  20.         }
  21.     }, {});

  22.     var FooLocal = can.Model.LocalStorage ({
  23. storageName: 'foo-canjs'
  24. }, {});


  25.     can.view( 'foo.ejs', Models.Foo.findAll() )
  26.         .then( function (frag) {
  27.             $("#app").html(frag);
  28.         }
  29.     );


Viewing all articles
Browse latest Browse all 3491

Trending Articles