Last active
October 6, 2017 14:11
-
-
Save tomazy/9800573 to your computer and use it in GitHub Desktop.
knockout + jquery chosen binding handler http://jsfiddle.net/tomazy/6A57J/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ko.bindingHandlers.chosen = { | |
init: function(element, valueAccessor, allBindings, viewModel, bindingContext){ | |
var $element = $(element); | |
var options = ko.unwrap(valueAccessor()); | |
if (typeof options === 'object') | |
$element.chosen(options); | |
else | |
$element.chosen(); | |
['options', 'selectedOptions', 'value'].forEach(function(propName){ | |
if (allBindings.has(propName)){ | |
var prop = allBindings.get(propName); | |
if (ko.isObservable(prop)){ | |
prop.subscribe(function(){ | |
$element.trigger('chosen:updated'); | |
}); | |
} | |
} | |
}); | |
} | |
} |
Please ignore my previous question: I forgot about the options binding and setting the optionsText and optionsValue, as can be seen here: http://knockoutjs.com/documentation/options-binding.html
For some reason I had to add some setTimeout to the $element.trigger('chosen:updated')
to get this gist working.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. This is working very nicely, thank you. I am using your fiddle: http://jsfiddle.net/tomazy/6A57J/. However, I am wondering how to provide a different text and value for the options. Example: say I have 2 fields: ID and Name... the Name should be displayed and ID should be sent back when posting the form. Something like this in the options:
<option value="{id}">{name}</option>
How can I achieve this with this binding handler? Could you please provide a fiddle? Thanks in advance!