2017-08-25 87 views
0

我遇到了Ember中的计算属性问题。无法获取计算属性内数组的值

有问题的产品timeZones,其设置是这样的:

import Ember from 'ember'; 

export default Ember.Route.extend({ 
    model(params) { 
    return Ember.RSVP.hash({ 
     account: this.store.findRecord('account', params.id), 
     timeZones: this.store.findAll('time-zone'), <------------ timeZones 
     users: this.store.query('user', { by_account_id: params.id }) 
    }); 
    }, 

    setupController(controller, model) { 
    this._super(controller, model.account); 
    controller.set('users', model.users); 
    controller.set('timeZones', model.timeZones); 
    } 
}); 

然后,我有一些所谓selectedTimeZone看起来像这样:

selectedTimeZone: Ember.computed('location.timezone', 'timeZones', function() { 
    console.log(this.get('timeZones')); 

    const timeZoneName = this.get('location.timezone'); 
    var result; 

    this.get('timeZones').forEach(function(timeZone) { 
     if (timeZone.name === timeZoneName) { 
     console.log('yes'); // <------------------- never gets here 
     result = timeZone; 
     } 
    }); 

    return result; 
    }), 

的问题是,this.get('timeZones')是不是真的在组件内部可访问。 timeZones使它成为模板就好了。我正在使用timeZones填充下拉菜单。但是当我console.log它,它只是作为Class来通过。

我怎样才能得到这个计算属性内的timeZones

回答

0

其实大部分这看起来不错,但是有些代码丢失了。就像这是一个组件或控制器,并且如果它的一个组件是如何被调用的?

然而,一个问题是显而易见的。 timeZone显然是ember-data记录,所以访问timeZone.name不是一个好主意。您应该使用余烬.get(),或者timeZone.get('name')Ember.get(timeZone, 'name')

接下来你的依赖关键是错误的。因为您使用每个timeZonename,所以应该用[email protected]替换相关性密钥timeZone

最后一点使用findBy您的CP的缩小版本:

selectedTimeZone: Ember.computed('location.timezone', '[email protected]', function() { 
    const timeZoneName = this.get('location.timezone'); 
    return this.get('timeZones').findBy('name', timeZoneName); 
}), 

如果这不工作你应该确认该数据成功加载到余烬检查商店,并确认您从控制器调用组件时,将timeZones传递到组件timeZones=model.timeZones