Gal Ben-Haim
Gal Ben-Haim

Reputation: 17803

Emberjs: what is the preferred way to load data into a controller?

I can think of 4 options:

1) in the router :

connectOutlets: function(router) {
    router.get('applicationController').connectOutlet(outlet, controller/view, router.get('store').findAll(Model);
}

this will invoke findAll each time the connectOutlet is invoked

2) in the controller's init:

App.MyController = Ember.ArrayController.extend({
    init: function() {
        this._super();
        this.set('content', App.router.get('store').findAll(Model));
    }
});

this will invoke findAll only when the controller is instantiated for the first time.

3) directly assign to the controller's content:

App.MyController = Ember.ArrayController.extend({
    content: App.router.get('store').findall(Model)
});

this will also invoke findAll only when the controller in instantiated for the first time, but if I do this, I get an error - Uncaught TypeError: Cannot call method 'get' of undefined so probably the router isn't instantiated yet.

4) call a controller's function to allocate data, from the router:

connectOutlets: function(router) {
    router.get('applicationController').connectOutlet(outlet, controller/view, router.get('store').findAll(Model);
    router.get('myController').getData();
}

App.MyController = Ember.ArrayController.extend({
    getData: function() {
        this.set('content', App.router.get('store').findAll(Model));
    }
});

same comments as the first option.

my question is, what is the preferred way or "Ember way" of allocating data in a controller ?

Upvotes: 2

Views: 991

Answers (1)

Bradley Priest
Bradley Priest

Reputation: 7458

I am pretty confident in saying that option 1 is the Ember way.

connectOutlets: function(router) {
  router.get('applicationController').connectOutlet(outlet, Model.find());
}

The issue with 2 & 3 is that you don't want to be loading data on controller initialization by default as this makes lazy-loading/paginating of data difficult.

It sounds like your main issue is the calling of findAll every time you enter a route. However if you are using the DS.RESTAdapter or similar this is a non-issue as the identity-map will catch the second call so the server will only ever be queried the first time.

Upvotes: 2

Related Questions