JSFiddle - React, Tailwind, and code Playground
by tomazy
HTML
<script src="//cdn.jsdelivr.net/chosen/1.1.0/chosen.jquery.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chosen/1.1.0/chosen.css">
<script src="http://knockoutjs.com/downloads/knockout-3.1.0.debug.js"></script>
<select multiple=true data-bind="
options: availableCountries,
selectedOptions: chosenCountries,
chosen: {width: '100%'}
">
</select>
<button type="button" data-bind="click: selectChile">Select Chile</button>
<pre> Available Countires: <span data-bind="text: availableCountries"/></pre>
<pre> Chosen Countries: <span data-bind="text: chosenCountries"/></pre>
JavaScript
ko.bindingHandlers.xchosen = {}
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);
['options', 'selectedOptions'].forEach(function(propName){
if (allBindings.has(propName)){
var prop = allBindings.get(propName);
if (ko.isObservable(prop)){
prop.subscribe(function(){
$element.trigger('chosen:updated');
});
}
}
});
}
}
function ViewModel(){
self = this;
self.availableCountries = ko.observableArray();
self.chosenCountries = ko.observableArray();
setTimeout(function(){
self.availableCountries(['Argentina', 'Chile', 'Poland']);
}, 1000);
}
ViewModel.prototype.selectChile = function(){
var hasChile = this.chosenCountries().some(function(a){
return a === 'Chile';
});
if (!hasChile)
this.chosenCountries.push('Chile');
}
var viewModel = new ViewModel;
ko.applyBindings(viewModel)