4

I have a model, which is fetched from the server. I would like to return a promise on creation, so that views that are using this model know, when to render. I could bind the promise to the window (or app), but a neater way would be to just return it, when the model is initialized (var promise = new app.User()). Is there a way to do this. And also: Is this a good way of handling async data?

app.User = Backbone.Model.extend({
    urlRoot: baseUrl+"/user",

    initialize: function(){
        this.promise = this.fetch();
        return this.promise; // Doesn't work ofc
    }

});
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
johnny
  • 8,696
  • 6
  • 25
  • 36

3 Answers3

1

There is https://github.com/kmalakoff/backbone-modelref .

But it seems it is better to split up assync and sync operations (i.e. fetching the data and instantiating objects). Fetch your models in app/ controllers / routers then create appropriate view and pass them to.

var model = new AppModel({ id: 123 });  
// state of model is semi-defined
model.fetch().then(function () {
  // state of model is completely defined
  var view = new AppModelView({ model: model });
  $('.placeholder').html(view.render().$el);
}).fail(function(reason) {
  var view = new AppErrorAlertView({ model: model, error: reason });
  ..
})

I suppose, in general, there is no good idea to make methods that operates asyncroniusly on model self state, because in this case the state of the model, in terms of other methods, is became undeterminated. In the example above I create an object at first with semi-determinated state. Alternatively, you can to use the factory pattern to hide indeterminacy from client code. For example use collections:

 var collection = new AppModelCollection();
 collection.fetch().then(function(){
     var model = collection.get(123); // state of model is completely defined.
 });
Evgeniy Generalov
  • 1,296
  • 14
  • 26
0

There's actually not much for you to do:

var myPromise = myModel.save();

Backbone already returns promises for methods interacting with the API.

David Sulc
  • 25,946
  • 3
  • 52
  • 54
0

You could use jquery deffered to return a promise object from a backbone model fetch. That way you have more control over the way the data is returned and you could also provide the success and failure callbacks in the model itself to log error etc. For example :

var model = Backbone.Model.extend({ 
  fetchData: function(){
    var def;
    def = $.Deferred();
    this.fetch({
    success : function(model,response,options) { 
                def.resolve(response);
              }
    error : function(model,response,options) { 
               def.reject(response);
             }
    }); 
    return def.promise();
  }

});
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39