I have a jquery ajax call defined like this
var fetchMessages = function(){$.getJSON(<some url>).then(function(data){ return data; }};
var messages = fecthMessages();
My routes are setup like this
App.Router.map(function() {
this.resource('messages', function() {
this.resource('message', { path: ':message_id' });
});
});
I use the promise messages in my routes like this
App.MessagesRoute = Ember.Route.extend({
model : function(){
return messages;
}
});
The above route works fine.
Next I have a nested route like shown below. This however errors out when I directly try to visit #/messages/<id of the message>. Loading #/messages followed by visiting #/messages/<id of message> works fine.
App.MessageRoute = Ember.Route.extend({
model: function(params) {
message = messages.findBy("id", params.message_id);
return message;
}
});
So how do I handle the promises in nested routes?
So how do I handle the promises in nested routes?
Apparently Ember handles these for you.
This however errors out when I directly try to visit #/messages/:
App.MessageRoute = Ember.Route.extend({
model: function(params) {
message = messages.findBy("id", params.message_id);
return message;
}
});
messages is still a promise, not an array; it doesn't have a findBy method. Instead, use
return messsages.then(function(m) {
return m.findBy("id", params.message_id);
});
Related
I have an app where we need to create an initializer that inject our global into all the route where our global is a function that load data from a JSON file and return the data.
global-variable.js
export function initialize(container, application) {
var systemSetting = {
systemJSON: function(){
return Ember.$.getJSON("system/system.json").then(function(data){
return data
});
}.property()
};
application.register('systemSetting:main', systemSetting, {instantiate: false});
application.inject('route', 'systemSetting', 'systemSetting:main');
}
export default {
name: 'global-variable',
initialize: initialize
};
index.js - route
export default Ember.Route.extend({
activate: function(){
var _settings = self.systemSetting.systemJSON;
console.log(_settings.test);
},
}
system.JSON
{
"test" : 100
}
the result of the console.log give me this
ComputedProperty {isDescriptor: true, _dependentKeys: Array[0], _suspended: undefined, _meta: undefined, _cacheable: true…}
I think it's because of the JSON is not loaded yet but after that I try to do something like this at route
index.js - route
activate: function(){
var self = this;
var run = Ember.run
run.later(function() {
var _settings = self.systemSetting.systemJSON;
console.log(_settings);
}, 1000);
},
but still give me the same log. Am I use wrong approach to this problem?
I finally found the answer. Because of what I want to call is from an initializer then one that I must do is to use .get and if I just using get then the one that I received is a promise and to get the actual data I must use .then
The code will look like this:
index.js - route
activate: function(){
this.get('systemSetting.systemJSON').then(function(data) {
console.log(data.test);
});
}
I am trying to do the following when visiting reviews/show (/reviews/:id):
Load two models from the server: One review and one user.
I only have access to the review's id, so I need to load it first, to get the userId
And then, when that has finished loading and I now have the userId, query the user using the userId attribute from the review
Finally, return both of these in a hash so I can use them both in the template
So two synchronous database queries, and then return them both at once in the model hook of the route.
I don't mind if it's slow, it's fast enough for now and I need it to work now.
This is what I've tried and it doesn't work:
reviews/show.js
export default Ember.Route.extend({
model: function(params) {
var user;
var review = this.store.findRecord('review', params.id).then(
function(result) {
user = this.store.findRecord('user', result.get('userId'));
}
);
return Ember.RSVP.hash({
review: review,
user: user
});
}
});
You can do this:
export default Ember.Route.extend({
model: function(params) {
var reviewPromise = this.store.findRecord('review', params.id);
return Ember.RSVP.hash({
review: reviewPromise,
user: reviewPromise.then(review => {
return this.store.findRecord('user', review.get('userId'));
})
});
}
});
The reason why user is undefined is because it hasn't been assigned in your first promise until the review is resolved, but Ember.RSVP.hash has received user as undefined.
I have a use case where all models relations in Ember Data are loaded async. I have a route which renders Grandparents in the example below based on whether the parent.child matches a particular model.
So far I've been able to manage to resolve the grandparent and parent model async loading but then my code becomes a massive jumble.
Are there any useful strategies for filtering out the grandparents without having to deal with promises at every level?
Example model definitions
App.Grandparent = DS.Model.extend({
...
parents: DS.hasMany('Parent', { async: true })
});
App.Parent = DS.Model.extend({
...
grandParent: DS.belongsTo('Grandparent', { async: true }),
child: DS.belongsTo('Child', { async: true })
});
App.Child = DS.Model.extend({
...
});
Code Sample
var client = this.modelFor('workspace.client');
var promise = new Ember.RSVP.Promise(function(resolve)
{
client.get('sessions').then(function(sessions)
{
Ember.RSVP.all(sessions.getEach('exercises')).then(function(exercises)
{
Ember.RSVP.all(exercises.getEach('exercise')).then(function()
{
console.log("RESOLVED");
resolve(sessions);
});
});
});
});
I think you can simple get away by chaining the promises.
var client = this.modelFor('workspace.client');
return client.get('sessions').then(function(sessions) {
return Ember.RSVP.all(sessions.getEach('exercises'));
}).then(function(exercises) {
return Ember.RSVP.all(exercises.getEach('exercise'));
}).then(function(allExercises) {
console.log("RESOLVED");
return allExercises;
});
note: not sure what you are trying to do when resolving with sessions, and not doing anything with the exercises
In my application, I've got an ApplicationAdapter whose ajaxError method is customized. Within that method, I'd like to be able to transition to a given route. How can I do this?
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR) {
switch(jqXHR.status) {
// [...]
case 401:
// How can I transitionTo('login') here?
}
// [...]
}
}
});
Instead of transition in the adapter, isn't a good pratice IMHO, you can return an instance of Error and handle it in the error action of the current route:
App.UnauthorizedError // create a custom Error class
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxError: function(jqXHR) {
var defaultAjaxError = this._super(jqXHR);
if (jqXHR) {
switch(jqXHR.status) {
case 401:
return new App.UnauthorizedError()
}
}
return defaultAjaxError;
}
});
App.IndexRoute = Ember.Route.extend({
model: function() {
return this.store.find('person');
},
actions: {
error: function(reason) {
// all errors will be propagated to here, we check the instance to handle the UnauthorizedError
if (reason instanceof App.UnauthorizedError) {
this.transitionTo('login')
}
}
}
});
If you want to use this for all routes, you can put the unauthorized transition in the ApplicationRoute. Because the ApplicationRoute is the parent of all routes, and not handled actions, or actions that return true, will bubble to the parent routes.
App.ApplicationRoute = Ember.Route.extend({
actions: {
error: function(reason) {
if (reason instanceof App.UnauthorizedError) {
this.transitionTo('login')
}
}
}
});
App.BarRoute = Ember.Route.extend({
actions: {
error: function(reason) {
// handle errors of bar route
// bubble to application route
return true;
}
}
});
This is a fiddle with this sample http://jsfiddle.net/SkCH5/
Throw the error and allow the error hook on the route to catch it and transition from there. Additionally you can make a mixin with this logic and add the mixin to all of your routes.
Machty has additional information in his gist talking about the new router: https://gist.github.com/machty/5647589
App.AuthenticatedRoute = Ember.Route.extend({
beforeModel: function(transition) {
if (!authTokenPresent) {
return RSVP.reject();
// Could also just throw an error here too...
// it'll do the same thing as returning a rejecting promise.
// Note that we could put the redirecting `transitionTo`
// in here, but it's a better pattern to put this logic
// into `error` so that errors with resolving the model
// (say, the server tells us the auth token expired)
// can also get handled by the same redirect-to-login logic.
}
},
error: function(reason, transition) {
// This hook will be called for any errors / rejected promises
// from any of the other hooks or provided transitionTo promises.
// Redirect to `login` but save the attempted Transition
var loginController = this.controllerFor('login')
loginController.set('afterLoginTransition', transition);
this.transitionTo('login');
}
});
I got the following simple ember.js-setup, which works all great
App.Router.map(function() {
this.resource('tourdates', function() {
this.resource('tourdate', { path: ':tourdate_id' });
});
});
App.TourdatesRoute = Ember.Route.extend({
model: function() {
return $.getJSON('http://someapi.com/?jsoncallback=?').then(function(data) {
return data;
});
}
});
App.TourdateRoute = Ember.Route.extend({
model: function(params) {
return tourdates.findBy('id', params.tourdate_id);
}
});
so, pretty simple, whenever i call index.html#/tourdates, i get the data via api. and when I click on a link in this view and call f.e. index.html#/tourdates/1 it just displays the view for its nested child.
This all breaks, when I directly call index.html#/tourdates/1 with the message
DEPRECATION: Action handlers contained in an `events` object are deprecated in favor of putting them in an `actions` object (error on <Ember.Route:ember174>)
Error while loading route: ReferenceError {}
Uncaught ReferenceError: tourdates is not defined
Although he makes the ajax-call to the api and gets the data, he is not able to initialize the nested model
When your App.TourdatesRoute is loaded, all data from the json, will be rendered. And when you click to edit one of these loaded objects, using a link-to for example, ember is smart enough to get the already referenced object, instead of send a new request. So your url will change to: yourhost.com/tourdate/id.
When you direct call this url, it will call the App.TourdateRoute model method. Because doesn't have any pre loaded data. But in your case you have a:
tourdates.findBy('id', params.tourdate_id);
And I can't see in any place the declaration of tourdates.
I recommed you to change your TourdateRoute to TourdateIndexRoute so when transitioning to tourdates the ajax call is performed once:
App.TourdatesIndexRoute = Ember.Route.extend({
model: function() {
return $.getJSON('http://someapi.com/?jsoncallback=?').then(function(data) {
return data;
});
}
});
The TourdatesRoute is called both for TourdateRoute and TourdatesIndexRoute, because it's the parent route of both. So fetching all data in the TourdatesIndexRoute will ensure this is just called when transitioning to tourdates.
In your TourdateRoute you will load just the record needed. Something like this:
App.TourdateRoute = Ember.Route.extend({
model: function(params) {
// retrieve just one data by id, from your endpoint
return $.getJSON('http://someapi.com/' + params.tourdate_id + '?jsoncallback=?').then(function(data) {
return data;
});
}
});
So a direct call to yourhost.com/tourdate/id will just loaded one record.
About your warning message, it happens because in some route you have:
App.MyRoute = Ember.Route.extend({
events: {
eventA: function() { ...},
eventB: function() { ...},
}
});
The events is deprecated and you need to use actions:
App.MyRoute = Ember.Route.extend({
actions: {
eventA: function() { ...},
eventB: function() { ...},
}
});
I hope it helps