我有一个非常简单的模型,由一个几乎空的控制器支持:
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,fyi。)
答案 0 :(得分: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
/ property
混淆不是真正的问题,而是您使用ObjectController
与ArrayController
的事实。这是SegmentsController
的样子:
// 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