Select2 w/ knockout
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<link rel="stylesheet" href="http://ivaynberg.github.com/select2/bootstrap/css/bootstrap.css">
<script src="http://ivaynberg.github.com/select2/select2-3.2/select2.js"></script>
<link rel="stylesheet" href="http://ivaynberg.github.com/select2/select2-3.2/select2.css">
<div>
<p>
In this Knockout / Select2 snippet: A setTimeOut function emulates an ajax call where data is retrieved to set the Modal data. In this case the selectedValue is set to 'g' after 0.25 seconds. It works fine for a normal select box however, it when select2 is used.
</p>
<h4>Example with Select2</h4>
<select style="width:300px" data-bind="select2: {}, options: values, value: selectedValueS2, optionsText: 'Text', optionsValue: 'Value'"></select>
<br />
<span data-bind="text: selectedValueS2"></span>
<h4>Example without Select2</h4>
<select style="width:300px" data-bind="options: values, value: selectedValue, optionsText: 'Text', optionsValue: 'Value'"></select>
<br />
<span data-bind="text: selectedValue"></span>
</div>
<hr/>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
JavaScript
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor) {
$(element).select2(valueAccessor());
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
},
update: function (element) {
$(element).trigger('change');
}
};
function ViewModel() {
var self = this;
self.selectedValue = ko.observable();
self.selectedValueS2 = ko.observable();
self.values = [{"Text": "red", "Value": "r" },
{"Text": "green", "Value": "g" },
{"Text": "blue", "Value": "b" }];
setTimeout(function () {
self.selectedValueS2('g');
self.selectedValue('g');
}, 250);
};
ko.applyBindings(new ViewModel());