简体   繁体   English

Backbonejs-如何侦听属于集合的集合中的更改

[英]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 SeatingChart具有“ Sections作为属性

A Sections is a collection of Section A SectionsSection的集合

A Section has a Seats as an attribute Section具有Seats作为属性

A Seats is a collection of Seat 一个Seats是集合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 ? 有没有,里面的方式SeatingChart听时到Seat被添加到的一个Section在S SeatingChartSections

I'm sure you know Backbone does provide this functionality out of the box. 我确定您知道Backbone确实提供了此功能。 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: 因此,让我们定义Seats集合:

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. 现在, Sections必须采取Seats动作并将其冒泡。

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: 最后,在您的SeatingChart集合中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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