Skip to content

Instantly share code, notes, and snippets.

@tomazy
Last active October 6, 2017 14:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tomazy/9800573 to your computer and use it in GitHub Desktop.
Save tomazy/9800573 to your computer and use it in GitHub Desktop.
knockout + jquery chosen binding handler http://jsfiddle.net/tomazy/6A57J/
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');
});
}
}
});
}
}
@gordon-matt
Copy link

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!

@gordon-matt
Copy link

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

@cederlof
Copy link

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