I’m new to Ember and I’m having a problem loading JSON from a URL. Here’s what I have:
var App = Ember.Application.create();
App.ApplicationController = Ember.Controller.extend();
App.ApplicationView = Ember.View.extend({ templateName: 'application' });
App.OrdersListController = Ember.Controller.extend();
App.OrdersListView = Ember.View.extend({ templateName: 'orders' });
App.Order = Ember.Object.extend();
App.Order.reopenClass({
find: function(){
//not implemented yet
},
findAll: function(){
var content = [];
$.ajax({
url: 'http://api.domain/orders',
dataType: 'jsonp',
success: function(response){
response.data.forEach(function(order){
this.content.addObject(App.Order.create(order))
}, this)
}
});
return this.content;
}
});
App.Router = Ember.Router.extend({
enableLogging: true,
// The initial state for the router, contains every other.
root: Ember.Route.extend({
goOrders: Ember.Route.transitionTo('orders'),
goLocations: Ember.Route.transitionTo('locations'),
goReports: Ember.Route.transitionTo('reports'),
goUsers: Ember.Route.transitionTo('users'),
goHelp: Ember.Route.transitionTo('help'),
//Authenticated routes
index: Ember.Route.extend({
route: '/',
redirectsTo: 'orders'
}),
orders: Ember.Route.extend({
route:'/orders',
initialState: 'index',
//Orders view.
index: Ember.Route.extend({
route: '/',
connectOutlets: function(router) {
router.get('applicationController').connectOutlet({
name:'ordersList',
context: App.Order.findAll()
});
}
})
})
})
});
App.initialize();
And in my template (simplified):
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="orders">
{{#each order in controller.content}}
<p>id: {{order.ord_id}}</p>
{{/each}}
</script>
With this I don’t get and error but nothing shows up. If I paste he JSON in the context of the connectOutlet it works though. Is there a problem with my findAll() function?
I would try this one:
As you see, i just removed the this pointer two times. I think the this pointer in this case points to an the Order class, which does not have a content property. But you want to reference the var you defined. Therefore it should be without this.
Note: I do also have trouble from time to time with the this pointer, when fetching data. But this structure has always worked for me so far. So it should work, but my explanation might not be perfect.