Backbone promise back

I have a model that is retrieved from the server. I would like to return the promise of creation, so that the representations using this model would know when to do it. I could associate a promise with a window (or application), but an easier way would be to simply return it when the model is initialized (var prom = new app.User ()). Is there any way to do this. And also: Is this a good way to handle asynchronous data?

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

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

});
+4
source share
2 answers

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

, , assync sync (, ). //, .

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 });
  ..
})

, , , , . . factory, . , :

 var collection = new AppModelCollection();
 collection.fetch().then(function(){
     var model = collection.get(123); // state of model is completely defined.
 });
+1

:

var myPromise = myModel.save();

Backbone promises , API.

0

Source: https://habr.com/ru/post/1532111/


All Articles