jeudi 11 février 2016

In Ember 2 with components how can I avoid using an observer when I want to create records alongside other record creation

As an example:

Lets say I have a model, Food.js with:

name: DS.attr('string'),
groupName: DS.attr('string'),
isMeat: DS.attr('boolean'),
kitchen: DS.belongsTo('kitchen', {async: true})

And I also have a model, Fridge.js with:

name: DS.attr('string'),
groupName: DS.attr('string'),
kitchen: DS.belongsTo('kitchen', {async: true})

These are collected together in a Kitchen Model:

name: DS.attr('string'),
foods: DS.hasMany('food', {async: true}),
fridges: DS.hasMany('fridge', {async: true})

I have a main component that manages creation of a kitchen. In a child component a user can create new foods in the store, and save to database. The component also allows users to edit foods already in the kitchen.

What I want to happen is that Fridge records are automatically created or deleted depending on how many fridges are required. Currently I would do this in the kitchen management component with an observer like this:

foodToFridgeMapper: function() {
  Ember.run.once(this, function() {
    // Loop through all the foods, populate requiredFridges based on isMeat and groupNames
    let requiredFridges = ...;

    // Compare required fridges to existing fridges
    // Call deleteRecord on any no longer required
    // Create record for any that don't exist and are required
    ...
  }
}.observes('kitchen.foods.[]', 'kitchen.foods.@each.isMeat', 'kitchen.foods.@each.groupName')

I hate observers. How can I achieve logic that creates and deletes records alongside another array, but avoiding them?


Note this question is similar to Ember — observe for creation/deletion of records but different in that the focus here is how to move everything outside of an observer and in a component situation, not controllers.

Aucun commentaire:

Enregistrer un commentaire