我正在处理的应用程序有一个事件页面,用户可以在其中查看来自他们自己和朋友的事件,以及能够使用内联事件创建者(在同一页面/路径上创建事件)。 为了更精确一点,事件全部加载并以新闻源样式显示,这完全没问题,但现在的问题是在尝试保存新的事件模型时。我认为一些代码会使这更容易理解。 路线:
this.resource('newsfeed', function() {
this.route('personal');
this.route('whatever');
});
然后在NewsfeedIndexRoute
应用
model: function() {
return App.Event.find();
}
用于在/ newsfeed中显示ArrayController
的所有事件。这很好。
此外,该应用还有NewsfeedRoute
和Controller
,因此可以在所有子路径上访问事件创建者,为了保存事件,我们有以下代码:
App.NewsfeedRoute = Ember.Route.extend({
setupController: function(controller){
controller.newRecord();
}
});
App.NewsfeedController = Em.ObjectController.extend({
newRecord: function() {
//The following line works but makes the API 'dirty' and an extra model needs to be created
this.set('content', App.Newsfeed.createRecord({title: "new title"}));
//The next line would be preferred, but overrides the displayed models at /newsfeed
//this.set('content', App.Event.createRecord({title: "new title"}));
},
save: function() {
this.get('model').save();
}
});
现在的问题是,当我转到/ newsfeed并使用行this.set('content', App.Event.createRecord({title: "new title"}));
时,它会覆盖newsfeed/index.hbs
模板中显示的所有内容,因为它只显示'新标题' )。当你输入更多显示的偶数创作者时。这显然不是我们想要的行为。理想情况下,它应该以某种方式分离,然后保存到服务器。
使用Newsfeed模型可以看到的另一条线是一种解决方案,它工作正常,但正如评论中提到的那样,它感觉非常像黑客,也使得API变得很脏,因为使用带有POST请求的/ events端点会更加RESTful。
所有人都有任何想法,如果现在有任何方法可以用ember-data实现这一目标吗?
答案 0 :(得分:2)
在ember中有很多方法可以实现这一点。看起来你很接近一个很好的解决方案,但在这种情况下缺少的是EventController。它看起来应该与App.NewsfeedController
中的内容非常相似。
App.EventController = Em.ObjectController.extend({
newRecord: function() {
this.set('content', App.Event.createRecord({title: "new title"}));
},
save: function() {
this.get('model').save();
}
});
现在,在您的模板中,使用{{render}}
帮助程序添加
{{render event}}
定义一个event.hbs模板。