Async in Emberjs
Async Routing
Reference to ember guide.
If you want to make sure model is ready before entering the target route. You could use async routing. How?
Make your model as Promise object in route’s model function.
For example: In year route i return a model that comes from ModelMgr.listMonth(params.year_id)
.
Because model is Promise object, i add a then
method to set id attribute to model(resolve will be model here)
1 2 3 4 5 |
|
In ModelMgr.listMonth
method, use Ember.RSVP.Promise
to wrap your function. Because i don’t return anything in the last line of function.
CoffeeScript will return the promise object automatically. months
will be the real model object.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Wait multiple function call ready
Sometimes you will use 3rd party library and it requires element existed in the DOM tree.
For example: I use highchartJS to draw diagram.
In the route it queries two models to finish the whole scenarios.
model
is the result from ModelMgr.listMonth
and modelForTrend
is the result from ModelMgr.queryTrend
.
The models all have attributes called isReady
with false default. After ModelMgr
get the data, it will set to true.
1 2 3 4 5 6 7 8 |
|
We have two attribute bindings to model’s attributes in controller.
1 2 3 |
|
Create a method to observe all attributes we care about. View shouldn’t connect to Model directly.
So i make drawLineChart
method to observe controller’s attribute.
1 2 3 4 5 6 7 8 9 10 11 |
|