Jeff
Jeff

Reputation: 2423

Bind a view to collections in backbone.js

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?

Upvotes: 3

Views: 11034

Answers (2)

danii
danii

Reputation: 5693

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!

Upvotes: 3

Venkat Kotra
Venkat Kotra

Reputation: 10743

Here is a nice tutorial I had followed long ago.

An Intro to Backbone.js: Part 3 – Binding a Collection to a View

It helps you define a DonutCollectionView that will, when given a collection of donuts, render an UpdatingDonutView for each donut.

Upvotes: 2

Related Questions