jeudi 31 mars 2016

ember data relationships and ready/loaded event

Until ember data has built-in dirty relationship tracking, we have rolled our own. After upgrading to Ember/Ember Data 2.4.3 (from something quite old), our custom solution stopped working.

The problem comes down to knowing when to make a snapshot of a record's relationship state as the "original" state against which we can compare later states.

Let's say an adapter's payload includes the following:

{
    id: 'post-1',
    type: 'post',
    relationships: {
        comments: {
            data: [{ type: 'comment', id: 'comment-1' }]
        }
    }
}

In the ready hook for the resulting record, and using the new references API, I'd expect to be able to say something like:

ready: function() {
    var commentIds = this.hasMany('comments').ids();
    // would expect commentIds to be ['comment-1']
}

But this seems not to work -- commentIds is an empty array.

(Note that observing the isLoaded property also doesn't seem to give me what I want—the record is already in the loaded state when the ready event fires.)

Basically I'd like to have something like a relationshipsLoaded event which is fired when a record's relationships have been populated with respect to an adapter's payload. The related records themselves may not be available or loaded, but that shouldn't impact the record's state of having a relationship, based on the data returned from an adapter.

After some spelunking I've found that hooking into the store's backburner will provide something that seems to work:

ready: function() {
    this.store._backburner.schedule('finished', this, function() {
        var commentIds = this.hasMany('comments').ids();
        // commentIds is now ['comment-1']
    });
}

But this is obviously sketchy and I'm not sure that it's really guaranteeing what I'd like it to be guaranteeing.

So: is there a real way to do this? A better way? Is this a feature that is forthcoming?

For reference I made a codepen illustration: http://ift.tt/1RNr0gQ




Aucun commentaire:

Enregistrer un commentaire