Search code examples
backbone.js

Backbone.js: Can a View or Collection have an attribute?


Lets say I have a list of boys and girls names. This collection of names also has a 'Gender' property.

I want to put a 'SelectedGender' attribute on either the Collection or the View so that I can fire a custom event only when the Selected gender changes.

Can a View be extended to have a attribute that fires a change event?

Can a Collection be extended to have a attribute that fires a change event?

Or am I forced to create another Model that contains a collection? I don't actually have code I'm just thinking design at this point.


Solution

  • To answer your question: Can a view or collection be extended to have an attribute that fires a change event, the answer is no and yes.

    No, you can't do view.set({attr: value}) or collection.set({attr: value})

    You can, however have a view or collection fire events by extending Backbone.Events.

    YourView = Backbone.View.extend({});
    _.extend(YourView, Backbone.Events);
    
    var view = new YourView();
    view.bind('SelectedGenderChanged', function() {
      console.log('SelectedGenderChanged event fired!');
    });
    
    //somewhere else in your code
    view.trigger('SelectedGenderChanged');
    

    However, there might be a better way to design this.

    If the selected gender changes when a user makes a selection from a combo box, then you can subscribe to the combo box change event in your view, and then have your view make any changes that need to be done at that time.