Rommel Castro
Rommel Castro

Reputation: 460

model returns null on controller

i'm working with a a router and a controller, and i need to complete some operations on the controller, this is my model code

AcornsTest.StockRoute = Ember.Route.extend({
  model: function(params) {
    "use strict";
    var url_params = params.slug.split('|'),
      url = AcornsTest.Config.quandl.URL + '/' + url_params[0] + '/' + url_params[1] + '.json',
      stockInStore = this.store.getById('stock', url_params[1]),
      today =  new Date(),
      yearAgo = new Date(),
      self = this;

    yearAgo.setFullYear(today.getFullYear() - 1);
    today = today.getFullYear()+'-'+today.getMonth()+'-'+today.getDate();
    yearAgo = yearAgo.getFullYear()+'-'+yearAgo.getMonth()+'-'+yearAgo.getDate();

    if(stockInStore && stockInStore.get('data').length) {
      return stockInStore;
    }

    return Ember.$.getJSON(url,{ trim_start: yearAgo, trim_end: today, auth_token: AcornsTest.Config.quandl.APIKEY })
      .then(function(data) {
        if(stockInStore) {
           return stockInStore.set('data', data.data);
        } else {
           return self.store.createRecord('stock', {
            id: data.code,
            source_code: data.source_code,
            code: data.code,
            name: data.name,
            description: data.description,
            display_url: data.display_url,
            source_name: data.source_name,
            data: data.data,
            slug: data.source_code+'|'+data.code
          });
        }
    });
  }
});

and this is my controller

AcornsTest.StockController = Ember.ObjectController.extend({
  init: function() {
    "use strict";

    this.send('generateChartInfo');
  },

  actions: {
    generateChartInfo: function() {
      "use strict";

      console.log(this.model);
      console.log(this.get('model'));
    }
  }
});

from the controller i'm trying to get access to the model to get some information and format it, and send it to the view but this.model or this.get('model') always returns null, how can i successful get access to the model from the controller? thanks

Upvotes: 6

Views: 2017

Answers (1)

givanse
givanse

Reputation: 14953

You are overriding the init method, but its broken, do this:

AcornsTest.StockController = Ember.ObjectController.extend({
  init: function() {
    "use strict";
    this._super();

    this.send('generateChartInfo');
});

You need to call the parent method.

See this test case: http://emberjs.jsbin.com/gijon/3/edit?js,console,output

The model is not ready at init time. If anyone has official docs please share.

Upvotes: 1

Related Questions