How to know when a Backbone model.fetch() completes?

坚强是说给别人听的谎言 提交于 2019-12-05 01:03:40

You can use the $.ajax success callback, but you can also just listen for the Backbone sync and error events on the model. sync fires after a successful call to the server, error fires after a failed call to the server.

this.model.on('sync', this.render, this);
this.model.on('error', this.handleError, this);

The fetch method can optionally accept has success and error callbacks; the simplest solution is to put you view's render in the success callback. You could also probably use the returned jqXHR promise, but if there's ever a case where the AJAX would be successful (per jQuery) but model initialization fails, that usage could be problematic.

I don't know what is your code structure, however if your are fetching your model inside your view, you can use something like this

var that = this;
this.model.fetch().done(function () {
    that.render();
});

else, if your are fetching your model outside your view, you can pass your promise to your view and make something similar

var promise = model.fetch();
// other code here
var view = new View({
    model: model,
    promise: promise
});

and inside your view, for example in initialize

View = Backbone.View.extend({
    initialize: function(){
        this.options.promise.done(function () {
            // your code here
        });
    }
});

How about this solution:

// emit fetch:error, fetch:success, fetch:complete, and fetch:start events
fetch: function(options) {
  var _this = this;

  options = options || {};

  var error = options.error;
  var success = options.success;
  var complete = options.complete;

  options.error = function(xhr, textStatus, errorThrown) {
    _this.trigger('fetch:error');
    if (error) error(xhr, textStatus, errorThrown);
  };

  options.success = function(resp) {
    _this.trigger('fetch:success');
    if (success) success.call(options.context, resp);
  };

  options.complete = function() {
    _this.trigger('fetch:complete');
    if (complete) complete();
  };

  _this.trigger('fetch:start');

  return Backbone.Model.prototype.fetch.call(this, options);
}

Link to gist https://gist.github.com/fedyk/23761ce1236c5673fb84

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!