0

我有一个由几乎空的控制器支持的非常简单的模型:

App.EnergySegment = Ember.Object.extend({
    identity: 'segment',
    isSelected: false,
});
App.SegmentController = Ember.ObjectController.extend({
    // simple properties
    debug: true,

    // actions
    actions: {
        toggleSegment: function() {
            var status = this.get('isSelected');
            this.set('isSelected', !status);
        }
    }
}); 

我有一个完全不同的控制器,需要计算所有选定段的成本:

App.DashboardController = Ember.ObjectController.extend({
    needs: 'segment',

    cost: function() {
        alert('a selection occurred!')
        return '1.00';
    }.property('controllers.segment.isSelected')
}); 

为什么当我选择一个细分时我的仪表板成本函数没有被触发?(我没有使用 Ember Data,仅供参考。)

4

1 回答 1

1

你正在混合property起来observes。计算属性仅在get().

App.DashboardController = Ember.ObjectController.extend({
    needs: ['segment'],

    cost: function() {
        var segment = this.get("controllers.segment");

        // Example: the cost changes if the segment selection
        // changes
        if(segment.get('isSelected')) {
          return '1.00';
        } else {
          return '0.00';
        }
    }.property('controllers.segment.isSelected'),

    // When the segment is selected/deselected, the alert
    // will pop up
    _selectedSegmentDidChange: function() {
        alert('a selection occurred!');
    }.observes('controllers.segment.isSelected'),
});

从评论看来,observes/混淆并不是真正的问题,而是您使用的是vs aproperty的事实。这是 a 的样子:ObjectControllerArrayControllerSegmentsController

// Mind the plural
App.SegmentsController = Ember.ArrayController.extend({
  selected: Ember.computed.filterBy('content', 'isSelected'),
});

由此,我们可以DashboardController在集合上进行工作:

App.DashboardController = Ember.ObjectController.extend({
  needs: ['segments'], // Mind the plural again

  // Make a shorter alias
  _selectedSegments: Ember.computed.alias("controllers.segments.selected"),

  cost: function() {
    var costs = this.get("_selectedSegments").getEach("cost");

    return costs.reduce(function(total, current) {
      return total + current;
    }, 0);
  }.property("_selectedSegments.@each.cost"),      
});

你可能想看看这个例子:http: //jsbin.com/ALIBewA/1/edit

于 2013-11-13T19:43:57.140 回答