Search code examples
javascriptbackbone.jsbackbone-eventsbackbone.js-collections

On and Off event doesn't work well


I create my view with a new collection.

I fire add and sync events :

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

Before fetch I do :

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

And when fetch is ok, in my sync callback :

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

But even if I put off the add event I everytime go in add event callback function when I fetch.


Solution

  • I'm going to suggest the following because I do not have any context on how you've architected your application (Backbone.js is great because it gives you a lot of rope, but how you architect your application can greatly change how you need to implement sync solutions). I'm more than happy to adjust, expand, or clarify this post if you can share a little more about how you've architected your App, View, Collection, and Model code for me to understand what you are trying to achieve.

    In your code, I would listen to the update event instead of the add event (since add triggers on each new item added to the collection, compared to update which triggers after any number of items have been added/removed from a collection). Then I would remove the on/off change for add event and instead have your view listen to Collection.reset event rather than turning off and on your listeners for your fetch/sync cycle.

    I've used this type of View design-pattern successfully in the past:

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