0

My app is made up of the following:

Collections:

  • Sections
  • Seats

Models:

  • Seat
  • Seating Chart
  • Section

A SeatingChart has a Sections as an attribute

A Sections is a collection of Section

A Section has a Seats as an attribute

A Seats is a collection of Seat

Is there a way to, inside the SeatingChart listen to when a Seat is added to one of the Sections in the SeatingChart's Sections?

ThomYorkkke
  • 2,061
  • 3
  • 18
  • 26
  • You never said what's the relation between `SeatingChart` and these things but nesting is not supported dirctly in backbone, you'll have to use plugins like backbone relational or something – T J Dec 27 '15 at 02:35
  • 2
    Possible duplicate of [How can I "bubble up" events on nested Backbone collections?](http://stackoverflow.com/questions/15856614/how-can-i-bubble-up-events-on-nested-backbone-collections) – anushr Dec 27 '15 at 05:54

1 Answers1

0

I'm sure you know Backbone does provide this functionality out of the box. So I'm going to assume that you'd like a suggestion of how to get this thing wired. The solution to follow is going to be specific to your design. For a generalization I suggest you look to Backbone Relational

You already put the first component of the solution which is to keep a reference to the collection you're tracking. This will come in handy as we move up the relationships.

But let's start at the bottom. The questions ask how to detect when a seat is added. So let's define the Seats collection:

var Seats = Backbone.Collection.extend({
  initialize: function () {
    this.setupListeners();
  },

  setupListeners: function () {
    this.on('add', _.partial(this.bubbleAction, 'add'));
    this.on('remove', _.partial(this.bubbleAction, 'remove'));
  },

  bubbleAction: function (action, model) {
    this.trigger('seats-action' action, model);
  }
})

Now Sections would have to pickup the Seats action and bubble it up.

var Sections = Backbone.Collection.extend({
  initialize: function () {
    this.setupListeners();
  },

  setupListeners: function () {
    this.listenTo(this.seats, 'seats-action', this.bubbleSeatsAction);
  },

  bubbleSeatsAction: function (action, model) {
    this.trigger('section:seats-action', this.sectionClass, action, model);
  }
})

And finally in your SeatingChart collection:

var SeatingChart = Backbone.Collection.extend({
  initialize: function () {
    this.setupListeners();
  },

  setupListeners: function () {
    this.listenTo(this.sections, 'section:seats-action', this.handleSeatAction);
  },

  handleSeatAction: function (section, action, model) {
    ///Logic goes here to handle a seat action///
})
seebiscuit
  • 4,905
  • 5
  • 31
  • 47