4
votes

I have a model for my sources and a model for each segment. Each source has many segments. Each segment has an action that toggles an isSelected property.

I need to keep an updated list of selected segments. My first thought was to do something like...

App.Source = Ember.Object.extend({
  selectedSourceList = Em.A(),

  selectedSourcesObserver: function() {
    // code to update array selectedSourceList
  }.observes('segment.isSelected')
});

.. but that observes() function isn't right. I'm new to ember, so my approach may be completely wrong.

How can a method in one model observe the properties of many other models?

EDIT: corrected names to indicate that the segment model is for a single segment - not a collection of segments (that is what I plan to do in the sources model).

1

1 Answers

6
votes

I think there are three parts to your question:

  1. how to observe a collection
  2. observers in general
  3. managing relationships

observing a collection

The @each property helps observe properties for items in a collection: [email protected]

observers in general

.observes() on a function is a shorthand to set up an observer function. If your goal for this function is to update a collection you might be better served by using .property() which sets up an observer and treats the function like a property:

selectedSegments: function() {
  return this.get('segments').filterProperty('isSelected', true);
}.property('[email protected]')

This means selectedSegments is the subset of segments from this object that are selected and is automatically managed as items are dropped or marked selected.

managing relationships

For plain Ember Objects you will need to manage the relationships, pushing new items into the array, etc.

segments = Em.A(), //somehow you are managing this collection, pushing segments into it 

Also note the difference between Ember Objects and Ember Models. Ember Data is an optional additional library that allows specifying models and relationships and helps to manage the models for you. With Ember data you might have something like:

App.Source = DS.Model.extend({

  //ember-data helps manage this relationship 
  //  the 'segment' parameter refers to App.Segment
  segments: DS.hasMany('segments'), 

  selectedSegments: function() {
    return this.get('segments').filterProperty('isSelected', true);
  }.property('[email protected]')
});

And App.Semgent

App.Segment = DS.Model.extend({
  selection: DS.belongsTo('selection')
});