Search code examples
javascriptdomeventsember.jsember-power-select

How to open and close Ember Power Select from outside


I'm aware of this question, but is not complete. I want to open and close the dropdown from outside.

I can dispatch a mousedown event when click on my wrapper component, so ember-power-select trigger opens!. But then if I click again it doesn't close. More precisely, it closes and opens again rapidly.

My assumption is the component is listening blur event to get closed, and then the mousedown arrives again and open the trigger.

Has anyone managed to get this to work? or an alternative?? I'm quite lost :)

Thanks for the help!

wrapper-component.js 

  didInsertElement() {

    this._super(...arguments);
    this.element.addEventListener('mousedown', (event) => {
      event.stopPropagation();
      const eventedElement = this.element.querySelector('.ember-power-select-trigger');
      const mouseDownEvent = new MouseEvent('mousedown');
      eventedElement.dispatchEvent(mouseDownEvent);
    });

  },


Solution

  • According to the docs, the only way to interact with the trigger/component is through the read-only API provided in subcomponents, blocks, and actions of the ember-power-select component.

    Since you can already open the trigger you can cache the API in an onchange event action defined in your component (or controller of the route) where you render the ember-power-select:

    Where you render the component just provide an action to onopen:

    {{#ember-power-select
      options=options
      selected=selectedOption
      onchange=(action "someAction")
      onopen=(action "cacheAPI")
      as |option|}}
      {{option}}
    {{/ember-power-select}}
    

    In your component or controller that renders it:

    actions: {
    
      cacheAPI(options) {
        if (this.powerSelectAPI) return;
    
        this.set('powerSelectAPI', options);
    
        // if you just want the actions:
        // this.set('powerSelectAPI', options.actions);
      }
    
    }
    

    Then you can open/close the trigger through the API:

    this.get('powerSelectAPI').actions.close();