mercredi 17 juin 2015

how to manage ember models dependency

I come from Rails and I'm learning ember. In Rails I am habit to do a massive use of model callbacks, where I put a lot of logic to keep consistency among them.

I started with the problem to delete associated objects when the parent is deleted. In Rails there is a :dependency option to provide to the has_many method in order to dispose what to do with associated records when the parent one is destroyed.

As I was not able to find anything similar or best practice on this but the existence of DS.Model events I started to implement that management myself:

/app/models/ledger.js

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  createdAt: DS.attr('date', {
    defaultValue: function() { return new Date(); }
  }),

  purchases: DS.hasMany('purchase', {async: true}),
  players: DS.hasMany('player', {async: true}),

  didDelete: function() {
    console.info('deleting associated records');
    Ember.RSVP.all([this.get('players'),this.get('purchases')]).then(
      function(associations) {
        associations.forEach(function(items) {
          items.forEach(function(item){
            console.debug(item.get('constructor.modelName') + ' ' + item.get('id'));
            item.destroyRecord()
          });
        });
      },
      function(err) {
        console.error(err);
      }
    );
  }

});

Before going too further I just wonder whether this is the way to go. In few words are DS.Model events callbacks the right place to keep consistency among models?




Aucun commentaire:

Enregistrer un commentaire