8

I have a view that takes a collection like below:

MyView = Backbone.View.extend({
    initialize: function() {
       this.collection.on("change://an attribute of a model in aCollectionToRender", someAction);
    }
});

var MyViewInstance = new MyView({
    collection: aCollectionToRender
});

Basically, I don't want MyView to listen for changes on the entire collection, only a single attribute of the model that the collection contains.

I realize there are a number of alternatives to this:

  1. Create views for each model of aCollectionToRender and attach .on("change") events in those views. I don't want to do this because it's not the right thing to do for my situation
  2. Just have a this.collection.on("change") event and have the event handler filter based on my requirements. This is less elegant, and if Backbone already allows me to write event filters as I asked above, this is duplicate code

I was just wondering if there's any way to write an event listener that already does the filtering. This question may also be a duplicate; I looked but I didn't find anything exactly like this, however, there are a lot of Backbone questions

Jay
  • 3,471
  • 4
  • 35
  • 49

1 Answers1

18

Maybe I am misunderstanding your question, but you can do exactly what you show. Check out the Backbone documentation.

MyView = Backbone.View.extend({
    initialize: function() {
       this.collection.on("change:attributeName", this.someAction /*function to call*/, this);
    },
    someAction: function(model, value, options){
    }
});
A F
  • 7,424
  • 8
  • 40
  • 52
Paul Hoenecke
  • 5,060
  • 1
  • 20
  • 20
  • 2
    Doh! I think you're right! For some reason I thought when it's a collection, the `attributeName` in `change:attributeName` referred to an attribute of the collection, not the model. – Jay Feb 05 '13 at 20:45
  • 1
    ok, but how can you do this: this.collection.on("change",function(model,property){ //get the property that was changed here... }); ??? – Alexander Mills Jul 24 '15 at 22:52