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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With