Search code examples
ember.jsexpressember-datasubdomainember-cli

how to add event for drop-down component to change subdomain by selected item


i use pod structure with ember cli. i have a 'drop-down' component.

in my drop-down.js component:

import Ember from 'ember';
  var component = Ember.Component.extend({
  tagName: '', //remove extra div wrapper.
  valueKey: 'id',
  textKey: 'text',
  options: [],
  value: null,
  defaultText: 'select...',
  selected: function () {
    var valueKey = this.get('valueKey');
    var textKey = this.get('textKey');
    var defaultText = this.get('defaultText');
    var fallbackOption = {};
    fallbackOption[valueKey] = 0;
    fallbackOption[textKey] = defaultText;

    if (Ember.isEmpty(this.get('value'))) {
      return fallbackOption;
    }

    var selected = this.get('options').findProperty(valueKey,this.get('value'));

    return selected ? selected : fallbackOption;
  }.property('options', 'value'),
  actions: {
    select(option) {
      var valueKey = this.get('valueKey');
      this.set('value', option[valueKey]);
    }
  }
});

export default component;

i have used this component in index to load countries.

in template.hbs for index :

 <div class="col-lg-3 col-md-3 col-sm-3 col-xs-6 input-padding">
   {{drop-down options=model.countries
     value=country
     valueKey=valueKey
     textKey=textKey
     defaultText=defaultText}}
 </div>

i want to add change event to countries dropdown, that it must change subdomain by country. for example, when i select Iran, its event causes my subdomain changes to 'Iran.site.com. how can i add this event? and where should i add it ?thanks


Solution

  • You can add an action to your component and when you select an option, you can send it up using the sendAction method.

    Your component will look like the below code. In that I have added an extra property action="countrySelected" where countrySelected is an action defined in either your controller or route.

    {{drop-down options=model.countries
      value=country
      valueKey=valueKey
      textKey=textKey
      defaultText=defaultText
      action="countrySelected"
    }}
    

    Now you need to modify the select action in your component code like

    select(option) {
      var valueKey = this.get('valueKey');
      this.set('value', option[valueKey]);
      this.sendAction('action', valueKey , option[valueKey]);
    }
    

    Here the last line is the relevant line. You are now calling the countrySelected action which can be defined either in the page's controller or route.