Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember JS, updating array not reflecting in views

Updating Ember JS array is not reflecting in views.

Controller

App.MyController = Ember.ArrayController.extend({
  results: [],
  init: function(){
    _this = this
    App.MyModel.find({}).then(function(contents) {
      obj1 = contents.objectAt(0)
      obj1.get('data').hasMany.results.forEach(function(item){
          _this.results.push(item)
      });
    })
    //rest of the code
  }
})

Template

{{#each results}}
  // show items of reults.
{{/each}}

This is the piece of code in which i am fetching data from server, and upon its loading, i am pushing it into results array. This loading for data from server takes some time, so template maps over the empty results array. Ideally, results array should update the things in template but logically it shouldn't.

Does any body know where i am missing? or doing wrong.

Thanks in advance.

like image 417
Nadeem Yasin Avatar asked Jun 21 '13 19:06

Nadeem Yasin


2 Answers

For bindings to work you have to use pushObject instead of push.

App.MyController = Ember.ArrayController.extend({
  results: [],
  init: function(){
    _this = this;
    App.MyModel.find({}).then(function(contents) {
      obj1 = contents.objectAt(0);
      obj1.get('data').hasMany.results.forEach(function(item){
        _this.results.pushObject(item)
      });
    })
    //rest of the code
  }
});

Fore more info on ember array pushObject please see here.

Hope it helps.

like image 134
intuitivepixel Avatar answered Oct 02 '22 08:10

intuitivepixel


I had a similar problem. The problem is that Ember doesn't get notified about the change in the array. In this case you have a special Ember function (pushObject) that replaces the standard Push and also notifies the framework of the change. But in other cases (for example Array.splice) you don't have such function, so you need to notify the framework manually. You can do this with:

this.notifyPropertyChange('array');
like image 23
Arntor Avatar answered Oct 02 '22 07:10

Arntor