thedeliciousmuffin thedeliciousmuffin - 1 month ago 20
Ajax Question

How can I load ember model after successful ajax call in Emberjs?

I have defined a model called

todo.js
in
app/models
like this:

export default DS.Model.extend({
title: DS.attr('string'),
created_at: DS.attr('date'),
updated_at: DS.attr('date'),
is_deleted: DS.attr('boolean'),
is_done: DS.attr('boolean')
});


Let's say I don't want to use to
ember-data
& I simply want to use plain old
ajax
like this:

export default Ember.Route.extend({
model() {
return Ember.$.getJSON('http://localhost:3001/todo').then((data) => {
// How would I load the data into the model here?
});
}
});


How would I load the data I am getting from the successful
ajax
call into the model?

I have defined a component to show todos like this:

<ul>
{{#each model as |todo index|}}
{{#link-to 'todo' todo.id}}<li>{{todo.title}}</li>{{/link-to}}
{{/each}}
</ul>


And here's the
router.js
:

Router.map(function() {
this.route('todos');
this.route('todo', { path: '/todo/:todo_id' })
});

Answer Source

You can use pushPayload method and peekAll .

export default Ember.Route.extend({
  model() {
    return Ember.$.getJSON('http://localhost:3001/todo').then((data) => {
       this.get('store').pushPayload('todo',data);
       return this.get('store').peekAll('todo');
    });
  }
});