Bind a view to collections in backbone.js

Jeff picture Jeff · Mar 8, 2013 · Viewed 11k times · Source

I'm semi-new to backbone. I'm trying to bind a collection to a view so that when a new model is added to a collection, the view is updated. I think when you do this with models you can bind to the model's change event. But how do you do the same with collections?

App.Views.Hotels = Backbone.View.extend({

    tagName: 'ul',

    render: function() {
        this.collection.each(this.addOne, this);
        var floorplanView = new App.Views.Floorplans({collection:floorplanCollection});
        $('.floorplans').html(floorplanView.render().el);
        return this;
    },

    events: {'click': 'addfloorplan'},

    addOne: function(hotel) {
        var hotelView = new App.Views.Hotel ({model:hotel});
        this.$el.append(hotelView.render().el);
    },

    addfloorplan: function() {
        floorplanCollection.add({"name": "another floorplan"});
    }
});

App.Collections.Floorplans = Backbone.Collection.extend({
    model: App.Models.Floorplan,
    initialize: function () {
        this.bind( "add", function() {console.log("added");} );
    }
});

The click event fires and adds to the collection. But how do I get it to update the view?

Answer

danii picture danii · Mar 8, 2013

You can listen to the collection's add event, which fires when a new item is added to the collection. In modern versions of Backbone, the method listenTo is preferred to bind or on for listening to events. (Read de documentation for more info)

For example, in your case this should do the trick:

App.Views.Hotels = Backbone.View.extend({

  initialize: function() {
    this.listenTo(this.collection,'add', this.addOne);
  },
  //rest of code

Hope this helps!