Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Backbone change event to attribute of model in a collection

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

like image 745
Jay Avatar asked Feb 05 '13 20:02

Jay


People also ask

Which function has to be used when you want to trigger the event only once before being removed?

js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.

What is El property of backbone JS view?

The Backbone. js View el method defines the element that is used as the view reference. this. el is created from the view's tagName, className, id and attributes properties, if specified.


1 Answers

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){
    }
});
like image 77
Paul Hoenecke Avatar answered Sep 20 '22 13:09

Paul Hoenecke