【发布时间】:2014-03-01 00:18:57
【问题描述】:
我不太完全确定为什么我的计算属性没有返回更新的值。
我有一个用户可以单击的选项列表,并且该操作会更新控制器的属性,即 Ember 对象。我有一个计算属性,它循环遍历该对象,查找该 Ember 对象属性具有非空值的键,如果找到,则返回 false,否则返回 true。
这里是东西:
App.SimpleSearch = Ember.Object.extend({
init: function() {
this._super();
this.selectedOptions = Ember.Object.create({
"Application" : null,
"Installation" : null,
"Certification" : null,
"Recessed Mount" : null,
"Width" : null,
"Height" : null,
"Heating" : null,
"Power" : null
});
},
selectedOptions: {},
numOfOptions: 0,
allOptionsSelected: function() {
var selectedOptions = this.get('selectedOptions');
for (var option in selectedOptions) {
console.log(selectedOptions.hasOwnProperty(option));
console.log(selectedOptions[option] === null);
if (selectedOptions.hasOwnProperty(option)
&& selectedOptions[option] === null) return false;
}
return true;
}.property('selectedOptions')
});
App.SimpleSearchRoute = Ember.Route.extend({
model: function() {
return App.SimpleSearch.create({
'SimpleSearchOptions': App.SimpleSearchOptions,
'numOfOptions': App.SimpleSearchOptions.length
});
},
setupController: function(controller, model) {
controller.set('model', model);
}
});
App.SimpleSearchController = Ember.ObjectController.extend({
getProductsResult: function() {
var productsFromQuery;
return productsFromQuery;
},
setSelection: function (option, selectionValue) {
this.get('selectedOptions').set(option, selectionValue);
this.notifyPropertyChange('allOptionsSelected');
},
actions: {
registerSelection: function(option) {
console.log('registering selection');
console.log(this.get('allOptionsSelected'));
console.log(this.get('selectedOptions'));
this.setSelection(option.qname, option.value);
},
控制器中的动作registerSelection 触发得很好,但我只看到SimpleSearch 模型中的console.log 一次。一旦第一次计算了属性,之后就不再关注它,这意味着每当调用它时,计算的属性都不会观察到 selectedOptions 的变化:
setSelection: function (option, selectionValue) {
this.get('selectedOptions').set(option, selectionValue);
this.notifyPropertyChange('allOptionsSelected');
},
编辑:
实际上我没有改变任何东西就解决了我的问题。
我更改了以下行:
this.notifyPropertyChange('allOptionsSelected');
到:
this.get('model').notifyPropertyChange('selectedOptions');
notifyPropertyChange 需要在模型(或具有特定属性的观察者的 Ember 对象)的上下文中调用,作为参数发送的字符串是更新的属性的名称。
在我进行更改后,它按预期工作。
【问题讨论】:
标签: javascript ember.js