【问题标题】:How to know when a Backbone model.fetch() completes?如何知道 Backbone model.fetch() 何时完成?
【发布时间】:2013-02-01 19:40:36
【问题描述】:

我像这样绑定我的主干模型的更改事件。

this.model.on( "change", this.render, this );

有时我想获取最新版本的模型并强制渲染视图。所以我这样做了

this.model.fetch();

不幸的是,model.fetch() 仅在新数据与之前存储在模型中的数据不同时才会触发更改事件。

如何在 fetch 完成时始终触发 this.render 回调,无论它是否触发 change 事件?

感谢(提前)您的帮助

【问题讨论】:

    标签: javascript backbone.js backbone-events backbone-model


    【解决方案1】:

    您可以使用 $.ajax 成功回调,但您也可以只监听模型上的 Backbone syncerror 事件。 sync 在成功调用服务器后触发,error 在调用服务器失败后触发。

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

    【讨论】:

      【解决方案2】:

      fetch 方法可以选择性地接受成功和错误回调;最简单的解决方案是将您的视图 render 放在成功回调中。您也可以使用返回的 jqXHR 承诺,但如果 AJAX 会成功(每个 jQuery)但模型初始化失败,那么这种用法可能会出现问题。

      【讨论】:

        【解决方案3】:

        我不知道你的代码结构是什么,但是如果你在视图中获取你的模型,你可以使用这样的东西

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

        否则,如果您在视图之外获取模型,您可以将您的承诺传递给您的视图并进行类似的操作

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

        在你的视图中,例如在初始化中

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

        【讨论】:

          【解决方案4】:

          这个解决方案怎么样:

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

          链接到要点https://gist.github.com/fedyk/23761ce1236c5673fb84

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-05
            • 2021-04-25
            • 2020-02-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多