user1156168
user1156168

Reputation: 956

Changing in model not affected on a view ember

I try to add data to model manually like this

beforeModel: function() {
    var scope =this;
    Ember.$.getJSON('/restURL').then(function(response){
                    scope.store.pushPayload('consultation',response);
},

and data successfully loaded, I can see it in ember debugger, but I have a problem - data is not render on a view.

template in application.hbs:

{{#each item in model}}
           {{#link-to 'consultation' item}}{{item.remoteUser.name}}{{/link-to}}
{{/each}}

NOTE: when I load data using this.store.find('consultation'); it's work fine, but I have custom URL and can't use this construction.

Upvotes: 0

Views: 76

Answers (2)

user663031
user663031

Reputation:

As I understand it, you want to load consultations using a direct ajax call. The way you are doing it now, the consultations are retrieved in beforeModel, then, since you are not returning the promise, Ember immediately proceeds to execute the model hook before the ajax calls completes. The this.store.find you have in the model hook is likely to make another, possibly invalid request to the server. The easiest way is simply

model: function() {
  var store = this.store;

  return Ember.$.getJSON('/restURL')
    .then(function(response) {
      store.pushPayload('consultation', response);
      return store.all('consultation');
    });
}

Note the use of store.all, which is a dynamic collection of all objects of that type already in the store.

You could also consider breaking the logic into beforeModel and model as in:

beforeModel: function() {
  return Ember.$.getJSON('/restURL')
    // this binding style is a matter of personal preference :-)
    .then(this.store.pushPayload.bind(this.store, 'consultation'))
},

model: function() {
  return this.store.all('consultation');
}

Upvotes: 2

nightire
nightire

Reputation: 1371

You should use afterModel hook instead of beforeModel, because beforeModel is not use for data aggregation. beforeModel occurs before the model try to get resolved, it can not access the resolved model, so you can't rely on it to add extra data to model.

On the other hand, afterModel hook will pass the resolved model in as the first argument, so you can further decorate the model as your needs, and you can return a promise just like the model hook.

Take look this simple example: http://emberjs.jsbin.com/nukebe/1

Upvotes: 0

Related Questions