Displaying the Right Data in Ember.JS : Part I
- User clicks on a link in the application
- Ember makes an AJAX request to the appropriate route in the API server
- The server responds with a JSON containing the requested data
- Ember receives the JSON data and stores in the the local store.
- Ember updates the appropriate sections of the views with data from the local store.
The important thing to note here is that once data is received from the API and stored in the local store, it will be available for display upon future requests without having to re-query the API. Only requests for new data will require communication with the API.
This flow leads to some interesting design conventions:
- It is the responsibility of the API to filter and serve the appropriate data for the view.
- Ember is usually limited to identifying the correct API route to query, storing whatever data was received in the local store and displaying it in the appropriate template.
Together, the flow and the conventions make it quite easy to render views of a users’s attributes and even a user’s data that is associated through hasMany or belongsTo relationships.
To illustrate, let’s review the following example where we want to show a Cyclist’s rides that he has signed up for. The relevant relationships are:
- a cyclist has many rides
- a ride has many cyclists
Working from the client side:
The view that we want to show is:
The above route handler will make a request for rides to the local store. If it cannot find the appropriate rides, it will trigger a request to the API and put them in the store. Then it will load all rides available in the store to the template. In part II of this series, we will see why the fact that all of the rides available in the store are loaded is very important. For now, let’s assume that this is the first time in the session that the user triggers this request. Ember will hit the ‘/rides’ route of the API which will route to the controller which processes the request in this manner:
The above controller responds to the ember request with a JSON containing all of the rides for the current cyclists (see Duncan Standish’s — my partner on this project — blogpost on setting a current user in Ember).
Once the data is received by Ember, it is stored in the local store, and ready for display in the template. The template makes use of the route handler’s model, which in this case is an array of rides, to display the rides like this:
which yields the view that we wanted:
In Part II of this series, we will explore some issues that arise when we want to display the same data class (e.g. rides)for other users from within the ‘current’ user’s profile.