目标
我正在尝试列出按日期范围分组的一系列事件。我的方法是创建一个EventGroup模型,其中包含一个事件列表。我没有定义EventGroups服务器端或使用fixture,而是想在客户端动态创建组(并在事件更新时保持同步)。
设置
window.App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter.extend();
App.Event = DS.Model.extend(
{
title: DS.attr('string'),
date_start: DS.attr('string'),
date_end: DS.attr('string'),
// ...
// Example of how an event can be classified into an event group
date_group: function( )
{
var groups = {'thisWeek': {start: moment().startOf('week'), end: moment().endOf('week')},
'nextWeek': {start: moment().add(1, 'week').startOf('week'), end: moment().add(1, 'week').endOf('week')},
'thisMonth': {start: moment().add(2, 'week').startOf('week'), end: moment().endOf('month')}
};
return function( )
{
var date = this.get('date_start');
for( group in groups )
{
if( date <= group.end && date >= group.start )
{
return group;
}
}
return date.getMonth();
}.property('date_start');
}(),
});
App.EventGroup = DS.Model.extend(
{
name: DS.attr('string'),
date_start: DS.attr('string'),
date_end: DS.attr('string'),
events: DS.hasMany('event')
});
App.EventGroup.FIXTURES = [];
途径
我可以从事件模型的init方法创建/更新事件组模型,但这看起来不是很干净,并且不能很好地封装逻辑。
App.Event = DS.Model.extend(
{
// ...
init: function( )
{
// update EventGroup models
this.store.createRecord('eventGroup',
{
// Proper event group creation data/code...
});
}
});
创建一个观察者似乎是一个好的方法,但我不知道在哪里设置它。我不认为在EventGroup模型中创建观察者是有道理的。
App.EventGroup = DS.Model.extend({
onEventAdded: function( )
{
// Proper event group creation code...
}.observes('App.Event')
});
扩展应用程序适配器似乎是最干净的方法,但我没有任何运气让它工作。我想覆盖createRecord,如果它是一个Event,则创建/更新相应的EventGroup。
App.ApplicationAdapter = DS.FixtureAdapter.extend(
{
init: function( )
{
console.log('init')
},
createRecord: function( )
{
console.log('create record')
this._super();
},
find: function( )
{
console.log('find')
this._super();
}
});
只记录'init'。 “创建记录”和“查找”不会显示在控制台中。
当然,如果有更好的方法可以解决这个问题,我全都听见了!