Skip to content

Instantly share code, notes, and snippets.

@bradstewart
Last active August 29, 2015 13:59
Show Gist options
  • Save bradstewart/10789879 to your computer and use it in GitHub Desktop.
Save bradstewart/10789879 to your computer and use it in GitHub Desktop.
Select2view
<select data-view="Select2NextTaskView" data-view-resource="task" data-bind="action.next_task_id">
<option></option>
<option data-foreach-task="options" data-bind-value="task.id" data-bind="task.title"></option>
</select>
class App.Select2View extends Batman.View
@option 'resource'
@::on 'viewDidAppear', ->
# Ensure this only fires once and isn't triggered by sub-views
return if @_selectEnabled
@_selectEnabled = true
# Set classes on the calling <select> node
node = $(@get('node'))
node.addClass('select2')
node.attr('style', 'width:100%')
@set('options', @loadOptions() )
node.select2({
minimumResultsForSearch: -1 #hide the search box
placeholder: @loadPlaceholder()
})
loadOptions: -> []
loadPlaceholder: -> ""
@bradstewart
Copy link
Author

I had a reason for creating the with data-foreach instead of passing the data directly to select2, but I honestly can't remember what it was.

@rmosolgo
Copy link

Nice! Yeah, foreach binding definitely seems more batman-y. Plus, it would play nicer with has-many associations that are being loaded. Otherwise, you'd have to observe the association set yourself and update Select2 when items were added or removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment