2
votes

I am trying to implement an action when a change to a model in a given collection is fired, but whenever I try to put a listener on the change, add, or remove events on my collection, no events are fired. When I attached a change event to a model's initialize function (just to test), the change event was fired successfully. The view below doesn't itself change the code, but I want it to re-render itself whenever a change to the collection has been made. It could be something wrong with my setup, but I want to get your advice. Below is my code:

contact.js (Model):

define([
  'jquery',
  'underscore',
  'backbone'
], function($, _, Backbone){

  var ContactModel = Backbone.Model.extend({
        urlRoot: '/contacts'
    });

  return ContactModel;
});

contacts.js (Collection):

define([
  'jquery',
  'underscore',
  'backbone',
  'models/contact'
], function($, _, Backbone, Contact){

  var ContactCollection = Backbone.Collection.extend({
    url: '/contacts',
    model: Contact
  });

  return ContactCollection;

});

contactlist.js (View):

define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/contactlist.html',
  'collections/contacts'
], function($, _, Backbone, contactListTemplate, Contacts){

  var ContactListView = Backbone.View.extend({
    el: '.contact-list',
    render: function(options) {
        var that = this;
        var contacts = new Contacts();
        contacts.on("add", function() {
            console.log('change');
        });
        contacts.fetch({
            success: function(contacts) {
                var results = contacts.models;
                if (options.query || options.query === '') {
                    var results = [];
                    var query = options.query.toUpperCase();
                    for (var contact in contacts.models) {
                        if (contacts.models[contact].get('firstname').toUpperCase().indexOf(query) !== -1 ||
                                contacts.models[contact].get('lastname').toUpperCase().indexOf(query) !== -1 ||
                                contacts.models[contact].get('email').toUpperCase().indexOf(query) !== -1 ||
                                contacts.models[contact].get('phonenumber').toString().toUpperCase().indexOf(query) !== -1)
                        {
                            results.push(contacts.models[contact]);
                        }
                    }
                    options.idclicked = null;
                }
                if (!options.idclicked && results[0]) {
                    options.idclicked = results[0].get('id');
                    Backbone.history.navigate('/contacts/' + results[0].get('id'), {trigger: true});
                }
                var template = _.template(contactListTemplate, {contacts: results, idclicked: options.idclicked});
                that.$el.html(template);
                $(document).ready(function() {
                    $('.contact-list').scrollTop(options.scrolled);
                });
            }
        });
    },
    events: {
        'click .contact': 'clickContact'
    },
    clickContact: function (ev) {
        $('.contact-clicked').removeClass('contact-clicked').addClass('contact');
        $(ev.currentTarget).addClass('contact-clicked').removeClass('contact');
        window.location.replace($(ev.currentTarget).children('a').attr('href'));
    }
  });

  return ContactListView;

});
2

2 Answers

2
votes

When running fetch(), the collection will trigger it's reset event, not add.

contacts.on("reset", function() {
    console.log('reset');
});

That will run as soon as the fetch completes, before your success callback.

change runs when the model itself has attributes changed, which you don't do anywhere in the code you posted.

Also generally I wouldn't access .models directly. I'd do this:

var results = contacts.toArray();
if (options.query || options.query === ''){
  results = contacts.filter(function(contact){
    return _.any(['firstname', 'lastname', 'email', 'phonenumber'], function(attr){
      return contact.get(attr).toString().toUpperCase().indexOf(query) !== -1;
    });
  }); 
// ...

Update

As it is now, you create the collection when you render. This is not a good idea because ideally you would want to be able to render again without fetching all of the data again.

I would move the collection creation logic into the view's initialize function like this:

initialize: function(options){
  this.collection = new Contacts();
  this.collection.on('reset add remove', this.render, this);
}

That way, as the collection changes, render is automatically triggered. This is complicated by your options, so I would try to change how you pass those arguments in. Maybe add a 'setOptions' function that saves the options to use while rendering. Ideally render will re-render the page identically to how it was before the call, it doesn't normally have arguments.

9
votes

Since Backbone 1.0 (change log), the answer to this question isn't 100% accurate anymore.

In Backbone 1.0+, you'll have to pass { reset: true } into the .fetch() method if you want the reset event to fire. See below.

Calling fetch on a collection will now trigger a 3 different events:


collection.fetch(); //triggers the following events
  1. request: Triggered before the ajax request is made
  2. add: (multiple times) this event will be triggered multiple times as each item in the data is added to the collection.
  3. sync: Triggered after data on the collection is synced with the data provider (data added to collection, ajax request completed)

To revert to the old style of backbone events, you need to call

collection.fetch({ reset: true }); //triggers the following events
  1. request: Triggered before the ajax request is made
  2. reset: Triggered when all data is placed into the collection.
  3. sync: Triggered after data on the collection is synced with the data provider (data added to collection, ajax request completed)

The best way to quickly see what events that your collection is triggering, is to bind to the all event and log the arguments:

collection.on('all', function() {
    console.log(arguments);
});