samedi 7 mai 2016

Pass data from application controller to child controller

I'm using Ember 1.13, I think some of this has been deprecated/changed in 2.x, but this project will not be upgraded.

Maybe I'm not going about this the right way, or missing something simple. Either way, what I need to do is add a new drink in a modal and then update the menu data with that new drink (as a row in a table).

I have a menu controller inside a parent admin controller (admin.menu). I have a modal where I'm adding data, and the modal seems to need to be in the application controller outside of any outlet, or else it does not render correctly. So, I'm adding the new drink within an action in the application controller.

// controllers/application.js
export default Ember.Controller.extend({
  menuController: Ember.inject.controller('admin.menu'),

  ...

  actions: {
    submitCustomDrink: function(){
      // action to create a new custom drink item
      let element = document.getElementById("custom-drink-name");
      let drinkType = element.value;

      Ember.$.ajax({
        'url': `${Config.apiRoot}store-drinks/custom/`,
        'method': 'POST',
        'data': {
          drink_name: drinkType
        }
      }).then(data => {
        // Add new drink to the existing drinks list
        let drinkArray = this.get("menuController.drinkArray");
        let drinkObject = {
          "drinkType": drinkType,
          "drinkSet": data
        };

        drinkArray.push(drinkObject);

        data.forEach(drink => {
          this.store.push('store-drink', drink);
          console.log(`pushed ${drink.type} of ${drink.size} into store`);
        });

        // reset modal input
        element.value = "";
      }, function(err){
        console.log('error', err);
      });
    }
  }
});

In that application controller, I'm injecting the menu controller which uses the data that I'm adding.

When I add a new drink, I'm expecting a table in templates/admin/menu.hbs to have an extra row. The rows are generated from a component that uses the drinkArray from the controller.

<tbody>

  

</tbody>

  • This code works when loading the page, gets all the drinks and creates the rows.
  • After adding the new drink and reloading the page, the new drink shows up, but I need it to show up without reloading page.
  • Through console logs in the application controller, I see that the this.get("menuController.drinkArray") returns the list of drinks, as well as returning the new drink as part of it after running drinkArray.push(drinkObject)
  • The new drink objects are also being pushed into the store correctly, according to ember inspector
  • I thought maybe it's updating the local variable rather than the menu controller property, so I also tried something like this.get("menuController").set('drinkArray', drinkArray), but have the same results



Aucun commentaire:

Enregistrer un commentaire