samedi 16 janvier 2016

EmberJS Load relationships in route

Ember.js with its relationships is still keeping me busy. Currently I'm trying to get grip on model relationships and loading them properly. I don't quite get how the RSVP mechanism works and promises are not entirely clear as well.

Imagine I have the following code:

// /app/application/adapter.js
import DS from 'ember-data';

export default DS.JSONAPIAdapter.extend({
    host: 'http://coursedev.api'
});

// /course/model.js
import DS from 'ember-data';

export default DS.Model.extend({
    order: DS.attr('number'),
    title: DS.attr('string'),
    body: DS.attr('string'),
    lessons: DS.hasMany('lesson')
});

// /course/route.js
import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return Ember.RSVP.hash({
            courses: this.store.findAll('course')
        });
    }
});

// /course/template.hbs
<ul>
{{#each model.courses as |course|}}
    <li >{{course.title}}

        <ul>
        {{#each course.lessons as |lesson|}}
            <li>{{ lesson.title }}</li>
        {{else}}
            <li>No lessons have been found.</li>
        {{/each}}
        </ul>

    </li>
{{else}}
    <li>No courses have been found.</li>
{{/each}}
</ul>

// /lesson/model.js
import DS from 'ember-data';

export default DS.Model.extend({
    order: DS.attr('number'),
    title: DS.attr('string'),
    body: DS.attr('string'),
    course: DS.belongsTo('course'),
    questions: DS.hasMany('question')
});

How do I set up the controller so that in the each-loop, the course.lessons also contains the right data? Now it just shows that no lessons have been found.

I tried all kinds of different things, such as:

// /course/route.js
import Ember from 'ember';

export default Ember.Route.extend({
    model() {
        return this.store.findAll('course').then(function(course){
            return Ember.RSVP.all(course.getEach('lesson')).then(function(lesson){
                return lesson;
            });
        });
    }
});

I also tried something with afterModel(), but that did not work out quite well. It must have something to do with RSVP, right? I just don't know where to look after many hours of trial and error.

IF it is possible eventually, is it then also possible to load another (nested) relationship in the each loop, e.g. courses.lesson.questions?

The data I'm using is not the problem here I guess, it can be seen here: http://ift.tt/1OiuRyt and http://ift.tt/1mKTVYh (lesson data is also available)




Aucun commentaire:

Enregistrer un commentaire