4

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).

4

1 回答 1

6

我认为您的问题分为三个部分:

  1. 如何观察一个集合
  2. 一般观察员
  3. 管理关系

观察一个集合

@each 属性有助于观察集合中项目的属性:segments.@each.isSelected

一般观察员

.observes()on a function 是设置观察者函数的简写。如果此函数的目标是更新集合,则最好使用.property()which 设置观察者并将函数视为属性:

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

这意味着selectedSegments是来自该对象的被选中的段子集,并在项目被删除或标记为选中时自动管理。

管理关系

对于普通的 Ember 对象,您需要管理关系,将新项目推入数组等。

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

还要注意 Ember 对象和 Ember 模型之间的区别。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')
});
于 2013-11-12T16:07:06.660 回答