Select2 w/ knockout
Select2 v4.0; Knockout v3.1
HTML
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/js/select2.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
<pre data-bind="text: ko.toJSON(selectedCountry, null, 2)"></pre>
Your country:
<select style="width:100%;" data-bind="options: $root.availableCountries,
optionsText: 'countryName',
optionsValue: 'id',
value: selectedCountry,
select2: { }">
</select>
<pre data-bind="text: ko.toJSON(noSelectedCountry, null, 2)"></pre>
Placeholder:
<select style="width:100%;" data-bind="options: $root.availableCountries,
optionsText: 'countryName',
optionsValue: 'id',
value: noSelectedCountry,
select2: { }">
</select>
JavaScript
ko.utils.setValue = function (property, newValue) {
if (ko.isObservable(property))
property(newValue);
else
property = newValue;
};
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
lookupKey = allBindings.lookupKey;
$(element).select2(obj);
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().select2Options || {};
for (var property in options) {
$(element).select2(property, ko.utils.unwrapObservable(options[property]));
}
$(element).trigger('change');
}
};
// Constructor for an object with two properties
var Country = function(name, population, price) {
this.countryName = name;
this.countryPopulation = population;
this.price = price;
this.id = price;
this.text = name;
};
var countries = [ new Country("UK", 65000000,1), new Country("USA", 320000000,2), new Country("Sweden", 29000000,3)];
var viewModel = {
availableCountries : ko.observableArray(countries),
selectedCountry : ko.observable(),
noSelectedCountry : ko.observable()
};
ko.applyBindings(viewModel);