javascript - Waiting for models to load before rendering app in Ember.js -
i have number of different application-level models — i.e., current user, current account, etc. — want load before rendering application. how , should done? this question/answer helped lot, doesn't cover async aspect.
the following code accomplishes want, loading models in beforemodel
(to take advantage of waiting promise resolve) doesn't seem right. should loading these models in applicationroute
?
app.applicationcontroller = ember.controller.extend({ currentaccount: null }); app.applicationroute = ember.route.extend({ beforemodel: function () { var self = this; return app.account.find(...).then(function (account) { self.controllerfor('application').set('currentaccount', account); }); } });
thanks help!
the trick return promise route's model method.
cause router transition app.loadingroute route, until promise resolves (which can used loading indication bars/wheels etc.)
when promise resolves, app.loadingroute deactivated, , original route's setupcontroller method called.
works ember-data promises, jquery's $.ajax promises , ember-model's fetch promises.
make sure return actual model after resolving promise.
can place handle errors if promise rejected - i'll leave other question.
as should load models - dependent on app's usage.
load model url indicates need model - rule of thumb indication of model id in url.
of course changes if need prefetch data.
and code:
app.someroute = ember.route.extend({ model: function(params){ return app.somemodel.fetch(params.model_id).then(function(modeldata){ // better return actual model here, , not promise return app.somemodel.find(params.model_id); }); }, setupcontroller: function(controller, model){ controller.set("model", model); // controller setup here - can omitted if no setup needed // run after promise has been resolved. } }); app.loadingroute = ember.route.extend({ activate: function(){ this._super(); // add loading indication here }, deactivate: function(){ this._super(); // remove loading indication } }
hope helps.
Comments
Post a Comment