Backbone - 区分由于获取引起的变化和来自前端的变化

Backbone - distinguish between change due to fetch and change from front-end

Backbone 是否有一个好的模式来区分由服务器获取导致的更改事件与由前端事件引起的更改事件?

       this.on('change',function(model){
                self.needsPersisting = true;
          });

例如:如果更改是服务器的结果,我不希望将 needsPersisting 标志设置为 true,但如果更改是前端的结果,我希望设置 needsPersisting标记为真。

如果您查看 Backbone 的注释来源,有一个模型的获取方法:

fetch: function(options) {
  options = _.extend({parse: true}, options);
  var model = this;
  var success = options.success;
  options.success = function(resp) {
    var serverAttrs = options.parse ? model.parse(resp, options) : resp;
    if (!model.set(serverAttrs, options)) return false;
    if (success) success.call(options.context, model, resp, options);
    model.trigger('sync', model, resp, options);
  };
  wrapError(this, options);
  return this.sync('read', this, options);
},

据我所知,'sync' 事件不仅会在该模型同步时触发,还会触发任何包含该模型的集合。

所以我似乎已经解决了它的方法是处理设置服务器属性时触发 'change' 事件的事实,因为知道 'sync' 事件将之后触发,这将覆盖我用于持久化模型的布尔标志,所以这似乎有效:

         var BaseModel = Backbone.Model.extend({

                needsPersisting: false,

                constructor: function () {
                    var self = this;
                    this.on('change',function(model,something){
                        self.needsPersisting = true; //fired when attributes are changed, regardless over whether from server or client
                    });
                    this.on('sync',function(){
                        self.needsPersisting = false; //sync event is fired on fetch after the change event is fired in the source
                    });
                    Backbone.Model.apply(this, arguments);
                }

           });

这个问题可以有多种解决方案。您可以根据您的要求选择您的解决方案:

1.根据变量名区分:

Backbone 中有一个解析函数(模型和集合都有该函数),只要服务器返回 model/collection 就会调用该函数。 我们可以覆盖该函数并在返回响应之前设置变量。

parse: function(response){
    // Setting variable value
    this.changedByServer = true;
    // Returning response as this will be mapped to model/collection
    return response;
}

2。根据事件区分

这种方法在可以接受服务器获取后重置 model/collection 的情况下很有用。 我们可以使用选项 "reset:true" 获取模型,当从服务器获取模型时它将触发 "reset" 事件。

modelObj.fetch({reset: true});

modelObj.on('reset', function(){
    // This handler is called when model gets fetched from server
});