Ember.js HasMany关系的检索模型
我有两种型号 时间输入Ember.js HasMany关系的检索模型,ember.js,ember-data,Ember.js,Ember Data,我有两种型号 时间输入 TimeTray.TimeEntry = DS.Model.extend({ startTime: DS.attr('date'), endTime: DS.attr('date'), status: DS.attr('string'), offset: DS.attr('number'), isDeleted: DS.attr('boolean'), task: DS.belongsTo('task'), dura
TimeTray.TimeEntry = DS.Model.extend({
startTime: DS.attr('date'),
endTime: DS.attr('date'),
status: DS.attr('string'),
offset: DS.attr('number'),
isDeleted: DS.attr('boolean'),
task: DS.belongsTo('task'),
duration: function () {
return TimeTray.timeController.duration(this.get('startTime'), this.get('endTime'));
}.property('startTime', 'endTime'),
title: function () {
if (this.get('task')) {
return this.get('task').get('title');
}
}.property('task')
});
任务
TimeTray.Task = DS.Model.extend({
title: DS.attr('string'),
totalTime: function () {
var timeEntries = this.get('timeEntries')
for (var entry in timeEntries) {
var duration = entry.get('duration')
}
}.property('timeEntries'),
isDeleted: DS.attr('boolean'),
isRecording: DS.attr('boolean', { defaultValue: false }),
timeEntries: DS.hasMany('TimeEntry')
});
如何获取时间条目实体数组,以便计算在任务上花费的总时间?上述方法不起作用
时间条目标题属性有效。您的代码中有一些错误: 1-在那个地方
...
for (var entry in timeEntries) {
var duration = entry.get('duration')
}
...
用于。。。在无法像预期的那样为数组工作的情况下,需要使用或for(var i;i
或array.forEach(func)
2-在computed属性totalTime
中,您将使用TimeEntry
的duration
属性,您需要使用属性('timeEntries.@each.duration')
指定依赖关系
3-可能会从服务器获取timeEntries
属性,因此您需要在定义中使用async:true
选项:
timeEntries: DS.hasMany('TimeEntry', { async: true })
4-如果您的timeEntries
始终为空,即使是保存在数据库中的数据。确保返回的json具有timeEntries ID。例如:
{id: 1, title: 'Task 1', timeEntries: [1,2,3] }
更改的代码如下所示:
TimeTray.Task = DS.Model.extend({
title: DS.attr('string'),
totalTime: function () {
var duration = 0;
this.get('timeEntries').forEach(function(entry) {
duration += entry.get('duration')
});
return duration;
}.property('timeEntries.@each.duration'),
isDeleted: DS.attr('boolean'),
isRecording: DS.attr('boolean', { defaultValue: false }),
timeEntries: DS.hasMany('TimeEntry', { async: true })
});
这就是这个样品的工作原理
我希望它能有所帮助您的
totalTime
方法既不求和timeEntry持续时间,也不返回值。此外,您的属性设置不正确(请使用)。正确的做法是:
totalTime: function () {
var timeEntries = this.get('timeEntries')
var duration = 0;
for (var entry in timeEntries) {
duration = duration + entry.get('duration');
}
return duration;
}.property('timeEntries.@each.duration'),
或者,更优雅地使用getEach()
和reduce()
:
我能知道为什么我的答案不被接受吗?嗨,我的问题不是javascript语言的动态性。我知道(…in…)的作用,结果我假设如果我在任务的时间项上创建了一个关系,ember会自动将时间项添加到任务中。但事实并非如此,因此我必须为任务返回一个带有timeEntry id的数组。如果你把这个加在你的答案上,我将很乐意重新接受它。我错过了这个。现在答案更新了。
totalTime: function () {
return this.get('timeEntries').getEach('duration').reduce(function(accum, item) {
return accum + item;
}, 0);
}.property('timeEntries.@each.duration'),