Reputation: 5212
I have a messages route and message sub route:
// routes
this.resource('messages');
this.resource('message', { path: '/messages/:message_id' });
Due to the backend architecture (Which I have no control over) I will need to call a separate ajax call for the messages (which is really a set of message previews - no messages, just subject) and the full message object.
However Ember ignores the message route model method when coming from the messages route? It does trigger it when that message route is called directly. How can I can I get Ember to always call the message route model method?
Here's what I currently have:
App.MessageRoute = Ember.Route.extend({
model : function (params) {
return Ember.$.ajax({
url: '/getMessage.do'
});
},
setupController: function (controller, model) {
console.log('model: ', model);
console.log('model set? : ', this.get('modelLoaded'));
var message = App.Message.create({
message: model.data.content
});
controller.set('model', message);
}
});
App.MessagesRoute = Ember.Route.extend({
model : function (params) {
return Ember.$.ajax({
url: '/getMessagePreveiws.do'
});
},
setupController: function(controller, model){
var messages = [];
model.data.forEach(function (message) {
messages.push(App.Message.create({
id: message.id,
subject: message.subject,
date: message.date_created,
read: message.read,
deleted: message.deleted
}));
});
controller.set('model', messages);
}
});
Upvotes: 0
Views: 441
Reputation: 691
Ember designed the model
hook to be used for going out and grabbing the appropriate data for your route when you don't have it. In your case, you're passing the data as a param via a link-to
helper, so Ember decides it doesn't need to run the model
hook since it already has the data.
setupController on the other hand, should always fire (at least I haven't found otherwise...). Since it sounds like you can go directly to the url and it works, keep the model hook the way it is, but add it's content with a promise to the setupController
hook:
setupController: function (controller, model) {
//Check if model has the data you were expecting
//and if it doesn't, use the model hook logic
if(Ember.isEmpty(model.data.content)){
Ember.$.ajax({
url: '/getMessage.do'
}).then(function(response){ // wait for the response...
var message = App.Message.create({
message: response.data.content
});
controller.set('model', message);
});
} else {
var message = App.Message.create({
message: model.data.content
});
controller.set('model', message);
}
}
Give that a try.
You can also check out beforeModel and afterModel to get a better idea of the route process and how they can be used as alternatives, though I think setupController is the best fit for what you're doing.
Upvotes: 2