问题
The app I am working on has an Event-page where users see Events from themselves and friends as well as being able to use an inline event-creator (to create events, on that very same page/route). To be a bit more precise, the events get all loaded and displayed in a newsfeed style, which works perfectly fine but the problem now is when trying to save a new event-model. I think some code will make this easier to understand. The routes:
this.resource('newsfeed', function() {
this.route('personal');
this.route('whatever');
});
then in NewsfeedIndexRoute
the app has
model: function() {
return App.Event.find();
}
for displaying all Events with an ArrayController
at /newsfeed. That works fine.
Furthermroe the app has a NewsfeedRoute
and Controller
as well so the event-creator is accessible on all sub-routes and for saving an Event we have the following code:
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();
}
});
So the problem now is, when I go to /newsfeed and use the line this.set('content', App.Event.createRecord({title: "new title"}));
it overrides everything that gets displayed in the newsfeed/index.hbs
template with that one model (so just displaying 'new title'). And when you type in more into the even-creator that gets displayed as well. This is obviously not the behaviour we want. Ideally it should just be separated somehow, then get saved to the Server.
The other line you can see with the Newsfeed model is a work-around and it works fine, but as mentioned in the comment it feels really like a hack and also makes the API kinda dirty, because using the /events endpoint with a POST request would be much more RESTful.
So does anyone have any idea, if there is any way to achieve that right now with ember-data?
回答1:
There are many ways to accomplish this in ember. Seems like you are pretty close to a good solution but what's missing in this case is an EventController. It should look a lot like what you'd had in App.NewsfeedController
.
App.EventController = Em.ObjectController.extend({
newRecord: function() {
this.set('content', App.Event.createRecord({title: "new title"}));
},
save: function() {
this.get('model').save();
}
});
Now in your template, use the {{render}}
helper to add the
{{render event}}
And define a event.hbs template.
来源:https://stackoverflow.com/questions/17800375/create-and-display-emberdata-models-on-same-route-resource