[英]Ember.js length of array of related objects
我正在使用Ember Data和Ember CLI。 我在兩個模型之間有一個簡單的一對多關系。 我正在嘗試創建一個計算屬性,該屬性返回附加到當前模型的項目數。
車型/ account.js
// Account model
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
notes: DS.hasMany('note', { async: true })
});
車型/ note.js
// Note model
import DS from 'ember-data';
export default DS.Model.extend({
body: DS.attr('string'),
date: DS.attr('number'), // unix timestamp
account: DS.belongsTo('account', { async: true })
});
控制器/帳戶/ index.js
// account/index controller
import Ember from 'ember';
export default Ember.ObjectController.extend({
oldNotesCount: function() {
var notes = this.get('notes');
console.log('=-=', notes.length); // undefined *****
return notes.length;
}.property('notes.@each')
});
notes.length
undefined
?
我已經簡化了這個示例...在我的情況下,我無法使用{{notes.length}}
,因為將會進行更多的計算-這只是第一步。
您已將notes
關聯標記為異步,因此this.get('notes')
返回一個promise。 承諾不具有length
屬性,因此undefined
。
要在異步關聯調用中獲取數據, then
在返回的諾言中使用函數作為參數。 關聯數據將作為第一個參數傳遞給該函數。
export default Ember.ObjectController.extend({
oldNotesCount: function() {
var _this = this;
this.get('notes').then(function(notes){
_this.set('oldNotesCount', notes.get('length');
});
return null;
}.property('notes.@each')
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.