I just started learning Ember.js (bought the PeepCode screencast), and am learning quite smoothly from it, but ran into a problem when trying to write my first Ember app.
Here's the (nested) route mapping:
App.Router.map(function () {
this.resource('bases', { path: '/' }, function () {
this.resource('base', { path: ':base_id' }, function () {
this.resource('places', function () {
this.resource('place', { path: ':place_id' });
});
});
});
});
This allows urls like this: domain.com/#/yokota-ab-japan/places/4c806eabd92ea093ea2e3872
yokota-ab-japan
is the id of a base (an Air Force base in Japan)
4c806eabd92ea093ea2e3872
is the id of a venue on Foursquare
When the places route is hit, I setup the data with a call to the foursquare api, iterate over the JSON to create an array of App.Place objects, and return that array.
App.PlacesRoute = Ember.Route.extend({
model: function () {
var placesData = Ember.A();
$.getJSON('https://api.foursquare.com/v2/venues/search?ll=35.744771,139.349456&query=ramen&client_id=nnn&client_secret=nnn&v=20120101',
function (data) {
$.each(data.response.venues, function (i, venues) {
placesData.addObject(App.Place.create({ id: venues.id, name: venues.name, lat: venues.location.lat, lng: venues.location.lng }));
});
});
return placesData;
}
});
That seems to work well. I display the placesData array using this template:
<script type="text/x-handlebars" data-template-name="places">
<div>
{{#each place in controller}}
{{#linkTo 'place' place}}
{{place.name}}
{{/linkTo}}
{{/each}}
</div>
{{outlet}}
</script>
The linkTo
links to the individual place, where I want to show more details about a place. Here's the route I setup to pull data about the single place, populate a single App.Place object, and return it:
App.PlaceRoute = Ember.Route.extend({
model: function (params) {
console.log('place route called');
var place;
$.getJSON('https://api.foursquare.com/v2/venues/' + params.place_id + '?client_id=nnn&client_secret=nnn',
function (data) {
var v = data.response.venue;
place = App.Place.create({ id: v.id, name: v.name, lat: v.location.lat, lng: v.location.lng });
});
return place;
}
});
My problem is, PlaceRoute
doesn't get called when the user clicks a link to it, but it does get called when the page is refreshed on this route.
According to the PeepCode Ember.js screencast (at ~12:25 into the video) it states that "controllers rarely ever make calls to data, route objects handle that", so I think I'm correct in putting my ajax calls in the routes (I've seen so many differing tutorials online, but since Peepcode consulted with the Ember.js creators, I went with it as my primary learning source).
If this isn't correct, or could be done better, please let me know.