On 和 Off 事件效果不佳

On and Off event doesn't work well

我使用新集合创建视图。

我触发添加和同步事件:

this.mapDetailsCOllection.on('add', self.onAddElement, self);
this.mapDetailsCOllection.on('sync', self.onSync, self);

在获取之前,我做的是:

this.mapDetailsCOllection.off("add");
this.mapDetailsCOllection.fetch();

当提取正常时,在我的同步回调中​​:

this.mapDetailsCOllection.on('add', self.onAddElement, self);

但即使我推迟添加事件,我每次获取时都会进入添加事件回调函数。

基于此:

The behavior of fetch can be customized by using the available set options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything:

collection.fetch({remove: false}) 

collection.set(models, [options]) 还有这个:

All of the appropriate "add", "remove", and "change" events are fired as this happens. Returns the touched models in the collection. If you'd like to customize the behavior, you can disable it with options: {add: false}, {remove: false}, or {merge: false}.

你可以通过

collection.fetch({add: false}) 

避免触发 add 事件。

我将提出以下建议,因为我对您如何构建应用程序一无所知(Backbone.js 很棒,因为它为您提供了很多帮助,但您如何构建您的应用程序应用程序可以极大地改变您需要实现同步解决方案的方式)。我非常乐意调整、扩展或澄清这一点 post 如果您可以分享更多有关您如何构建应用程序、视图、集合和模型代码的信息,以便我了解您的尝试实现。

在你的代码中,我会监听 update 事件而不是 add 事件(因为 add 在每个添加到集合的新项目上触发,相比 update 触发 任何数量的项目已经 added/removed 来自一个集合)。然后我会删除 on/offadd 事件的更改,而是让您的视图收听 Collection.reset 事件,而不是关闭和打开您的听众你的 fetch/sync 周期。

我过去成功地使用过这种类型的视图设计模式:

var _ = require('lodash');
var DocumentRow = Backbone.View.extend({
  events: {
    "click #someEl": "open"
  },

  clean: function() {
    // cleans up event bindings to prevent memory leaks
  },

  initialize: function(options) {
    _.bindAll(this, [
      'initialize',
      'open',
      'render',
      'clean'
    ]);

    options = options || {};
    this.collection = options.collection ? options.collection : SomeCollection;
    this.listenTo(this.collection, "reset", this.render);
  },

  open: function(item) {
    ...
  },

  render: function() {
    ...
  }

});