backbone.jsbackbone-relational

Listen in Backbone view to nested Backbone Relational model events


Say I have a Backbone Relational model representing a crowd - it has a related collection of People, each of model type Person:

CrowdModel = Backbone.RelationalModel.extend({
     relations: [{
        type: Backbone.HasMany,
        key: 'People',
        relatedModel: 'PersonModel',
        collectionType: 'Backbone.Collection'
     }]
});

Each Person has a related collection of Children, a child also being of model type Person:

PersonModel = Backbone.RelationalModel.extend({
    relations: [{
        type: Backbone.HasMany,
        key: 'Children',
        relatedModel: 'PersonModel',
        collectionType: 'Backbone.Collection'
    }]
});

Now, in my view, I'd like to listen to a change event - let's call it "Hungry" - on any of the models.

CrowdView = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.model.get("People"), 'change:Hungry', this.hungryChange);
    },
    hungryChange: function(model, val, options) {
       if(val) console.log("Somebody's hungry!");
    }
});

This will fire if any of the People are hungry, but I'm looking to find a way in the view to also listen for the hungry event on any of the Children. Is there some way of bubbling this up?

jsfiddle here: http://jsfiddle.net/fnj58/1/

Sorry for the contrived example - this really has to do with a model representing a tree of checkboxes, but it's easier to describe this way.


Solution

  • You should bubble the event from the Person.

    Add handler for childHungry in CrowdView init function

    CrowdView = Backbone.View.extend({
              ....
      initialize: function () {
        this.listenTo(this.model.get("People"), 'childHungry', function(){
          console.log("Someone's child is hungry");
        });// listening to child hungry
        this.listenTo(this.model.get("People"), 'change:Hungry', this.hungryChange);
      },
    });
    

    Person model should listen to his children and trigger that he has a child hungry

    PersonModel = Backbone.RelationalModel.extend({
          .... 
      initialize: function(){
        this.listenTo(this.get("Children"), 'change:Hungry', this.childHungry);
      },
      childHungry: function(){
        this.trigger("childHungry");
      }
    

    By the Way: if you don't want the Crowd to distinguish between a child hungry or a person hungry you could also just trigger change:Hungry on the above childHungry function and keep your versiono CrowdView (See http://jsfiddle.net/fnj58/2/)