How to call a controller function in the EmberJS component

0

I have a radio-button.js component, a controller radio-options.js, and the radio-options.hbs template. I need to call the optionChanged function that is of the controller in the component, currently the form that is gives the following error: Uncaught Error: had the handler action for: optionChanged

COMPONENT

import Ember from 'ember';

var RadioView = Ember.Component.extend({
  tagName: 'input',
  type: 'radio',
  attributeBindings: ['type', 'htmlChecked:checked', 'value', 'name'],

  change: function(){
    this.set('selectedValue', this.get('value'));
    this.sendAction('optionChanged', this.get('value'));
  },

  htmlChecked: function(){
    return this.get('value') === this.get('selectedValue');
  }.property('value', 'selectedValue'),

  setupBindings: function() {
    if (this.binding) {
      this.binding.disconnect(this);
    }
    this.binding = Ember.Binding.from("context." + this.get('checked')).to('selectedValue');
    this.binding.connect(this);
  }.on('init').observes('checked', 'context')

});

export default RadioView;

CONTROLLER

import Ember from 'ember';

var RadioOptionsController = Ember.Controller.extend({
  answer: Ember.computed.alias('parentController.answer'),

  radioName: function(){
    return 'question-' + this.get('parentController.model.id');
  }.property('parentController.model'),

  actions: {
    optionChanged: function(selectedValue) {
      console.log('value: '+selectedValue);
      this.get('answer').set('text', selectedValue);
      this.send('saveAnswer');
    }
  }
});

export default RadioOptionsController;

TEMPLATE

{{#each model as |option|}}
  <li>
    <label>{{radio-button name=radioName checked='answer.text' value=option.text}} {{option.text}}</label>
  </li>
{{/each}}
    
asked by anonymous 30.03.2016 / 15:01

1 answer

1

In your component call in the template, you need to pass the optionChanged to the component. As in the code below.

Template

{{#each model as |option|}}
  <li>
    <label>{{radio-button name=radioName checked='answer.text' value=option.text optionChanged='optionChanged'}} {{option.text}}</label>
  </li>
{{/each}}

And in the component you need to do the following

var RadioView = Ember.Component.extend({
  // Tirei o código para não causar confusão, mas é só adicionar ele.
  actions:{
    checkedValue: function(value) {
      this.sendAction('optionChanged', value);
    }
  }
});

And in your controller you define something to deal with this action, if in the controller.

var RadioOptionsController = Ember.Controller.extend({
   actions: {
     optionChanged: function(value) {
       //trata a chamada e o que precisa aqui com o seu valor. 
     }
   }
});
    
30.03.2016 / 15:12