简体   繁体   中英

Backbonejs - How to listen to a change in a collection that is part of a collection

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 Section s in the SeatingChart 's Sections ?

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///
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM