Ember.js: How can one model observe other models?

I have a model for mine sourcesand a model for everyone segment. Each source has many segments. Each segment has an action that switches the property isSelected.

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 the observes () function is incorrect. I am 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 one segment and not a set of segments (this is what I plan to do in the source model).

+4
source share
1 answer

I think there are three parts to your question:

  • how to watch the collection
  • observers in general
  • Relationship management

collection observation

The @each property helps to observe the properties of elements in the collection: segments.@each.isSelected

observers in general

.observes()by function is an abbreviation for setting the observer function. If your goal for this function is to update the collection, you might be better off using .property()one that sets an observer and treats the function as a property:

selectedSegments: function() {
  return this.get('segments').filterProperty('isSelected', true);
}.property('segments.@each.isSelected')

This means that selectedSegments- this is a subset of segments from this object that are selected and automatically controlled as elements are deleted or marked.

relationship management

Ember , ..

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

Ember Objects Ember Models. Ember Data - , . Ember - :

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('segments.@each.isSelected')
});

App.Semgent

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

All Articles