Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ember.js pushObject not pushing

Tags:

ember.js

Getting my brain wrapped around emberjs. Trying to create a controller that loads objects from a webservice call that returns a JSON array:

(Note that this is javascript generated from coffeescript)

MTM.Trade.controller = Ember.ArrayController.create({
  loadAll: function() {
    var self;
    self = this;
    this.set('content', []); /* fails with or without this line*/
    return $.getJSON('http://localhost:8080/webservice/trades', function(data) {
      var jsonTrade, trade, _i, _len;
      console.log("Length = " + data.length);
      for (_i = 0, _len = data.length; _i < _len; _i++) {
        jsonTrade = data[_i];
        trade = MTM.Trade.create(jsonTrade);
        self.pushObject(trade);
      }
      console.log("Everything pushed");
    });
  }
});

Upon calling MTM.Trade.controller.loadAll(), it's clear that the loop is being called for each object. However my controller never changes.. running console.log MTM.Trade.controller.get('content') returns a blank array.

I know that ember-rest and ember-data exist, but for now I'm rolling-my-own to learn how to do these things myself, and the will migrate to those frameworks later.

UPDATE

Thanks to this article I did get the answer to my question.. I need to init my array as such:

MTM.Trade.controller = Ember.ArrayController.create({

  init: function() {
    this._super();
    return this.set('content', Ember.A());
  },

loadAll: function() {
    ...

So now my question is, why? Intuitively shouldn't the ArrayController initializer take care of this? Perhaps this is not the way an ArrayController is expected to be used?

like image 628
Roy Truelove Avatar asked Nov 13 '22 00:11

Roy Truelove


1 Answers

Before your update, I put a comment, where I told you to initialize the content at creation time (so in the hash of the create).

MTM.Trade.controller = Ember.ArrayController.create({
    content: [],
    //...
});

But then I saw that you were setting content to [] in the loadAll function. So I was thinking that initialization was unnecessary.

When looking closest to ArrayController, it's just an extension of the ArrayProxy mixin, (ie: kinds of interface), so when creating an instance of an ArrayController, you must define the content property.

like image 72
sly7_7 Avatar answered Dec 27 '22 00:12

sly7_7