A chosen.js select filled via Ember.js

We have a lot of chosen in our ember app, and extracted this superclass to make interaction with them easier, it takes care of refreshing/filling/selecting stuff.

// fix chosen picks up ember script tags -> weird output when search for t or i
// this breaks the bindings within the options tags
// works around https://github.com/harvesthq/chosen/issues/581
App.UnboundSelectOption = Ember.SelectOption.extend({
  template: Ember.Handlebars.compile('{{unbound label}}')
});

App.ChosenSelect = Ember.Select.extend({
  chosenOptions: {},

  template: Ember.Handlebars.compile(
    '{{#if prompt}}{{unbound prompt}}{{/if}}' +
    '{{#each content}}{{view App.UnboundSelectOption contentBinding="this"}}{{/each}}'
  ),

  didInsertElement: function(){
    this._super();
    this.$().chosen(this.chosenOptions());
  },

  _closeChosen: function(){
    // trigger escape to close chosen
    this.$().next('.chzn-container-active').find('input').trigger({type:'keyup', which:27});
  },

  rerender: function(){
    if(this.get('state') == 'inDOM'){
     // remove now disconnected html
      this.$().next('.chzn-container').remove();
    }
    this._super();
  },

  rerenderChosen: function() {
    this.$().trigger('liszt:updated');
  }
});

3 thoughts on “A chosen.js select filled via Ember.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s