Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have view listen to collection event

Tags:

backbone.js

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?

like image 711
Randomblue Avatar asked Dec 21 '11 20:12

Randomblue


2 Answers

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 });
like image 104
Paul Avatar answered Oct 21 '22 13:10

Paul


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});
like image 26
Helgi Borg Avatar answered Oct 21 '22 13:10

Helgi Borg