Randomblue
Randomblue

Reputation: 116273

Have view listen to collection event

I have a view myView and a collection myCollection. When I add a model to myCollection, the add event is triggered by myCollection. How can I have myView listen to that add event?

Upvotes: 10

Views: 14508

Answers (3)

Helgi Borg
Helgi Borg

Reputation: 876

After ver. 0.9.9 (added Dec. 13, 2012) it is recommended to use listenTO.

In line with this:

var MyView = Backbone.View.extend({

    initialize: function() {
        this.listenTo(this.collection, 'add', this.onModelAdd);
    },
    onModelAdd: function(model) {
        // do something
    }
});

var myCollection = new MyCollection();
var myView = new MyView({collection: myCollection});

Upvotes: 11

Andreas Köberle
Andreas Köberle

Reputation: 110892

You have to bind your view to listen on the "add" event of your collection:

var MyView = Backbone.View.extend({
    initialize: function(){
        this.collection.bind('add', this.somethingWasAdded, this)
    },
    somethingWasAdded: function(){

    }
});
new MyView({collection: myCollection})

Upvotes: 3

Paul
Paul

Reputation: 18597

You can pass the collection to the view when you instantiate it, and then you can have the view bind to the add event on the collection in the initialize method.

Here's a code example

MyView = Backbone.View.extend({
  initialize: function() {
    this.collection.bind('add', this.onModelAdded, this);
  },

  ...other view functions

  onModelAdded: function(addedModel) {
    //do something
  }
}

And this is how you pass the collection in when you instantiate the view

var view = new MyView({ collection: myCollection });

Upvotes: 18

Related Questions