In my last post, I told you how I was working on an Ember project using a lot of UI libraries. One of those libraries is Chosen from the team at Harvest.

Chosen provides some gorgeous select boxes with search functionality that aim to make selects less ugly and more useful. Chosen is wonderful, except that it is script-heavy and if you don't know what you now know from my previous post, it's not easy to work with from an Ember perspective.

Andriy Buday has an awesome implementation of a Chosen multi-select using Ember Components. (Here is the just the gist.)

I was able to use Andriy's code and implement a single-select version. I don't need multi-selects in my app, and I have an inkling that you might run into issues if you try and use Andriy's and my code alongside one another. That can be solved by simply naming the components differently.

The component code is below. The first thing you'll notice is that I'm using Coffeescript. Also, I removed Andriy's default settings because I was running into issues with them. Other than that, his lines 53-55 became my line 36, and his 63-72 became my 44-48.

I hope this helps you out. If you need me to clear anything up, comment or send me a tweet @MattAHorton.

App.InputChosenComponent = Ember.Component.extend(
  init: ->
  # view properties
  labelClasses: (->
    @get("labelClass") + " control-label"
  inputContainerClasses: (->
    @get("inputContainerClass") + " input-group"
  inputClasses: (->
    @get("inputClass") + " form-control chosen-select"
  disabledFixer: (->
    chosenSelect = @$(".chosen-select")
    chosenSelect.prop("disabled", @get("intputDisabled")).trigger "chosen:updated"
    chosenSelect.trigger "chosen:updated"
  # dom stuff
  setup: (->
    chosenSelect = $(".chosen-select")
    # styling setup
    chosenSelect.attr "data-placeholder", @get("dataPlaceholder")
    $(".chosen-choices").addClass @get("inputContainerClass")
    $(".search-field > input").addClass "form-control"
    # initial values
    optionValueName = @get("optionValuePath").replace("content.", "")
    currentSelection = @get("chosenSelection").get optionValueName
    chosenSelect.val currentSelection
    chosenSelect.prop("disabled", @get("intputDisabled")).trigger "chosen:updated"
    chosenSelect.trigger "chosen:updated"
    # handling changes
    self = this
    chosenSelect.chosen().change (event, item) ->
      if item.selected
        val = parseInt(item.selected)
        selectedItem = self.get("content").findBy(optionValueName, val)
        self.set "chosenSelection", selectedItem
  teardown: (->