KO Chosen
by Jimmy Chandra
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.0/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="http://harvesthq.github.io/chosen/chosen.css">
<script src="//ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.9.1/themes/smoothness/jquery-ui.css">
<h3>Free Trial Extender</h3>
<label>Company</label><br>
<select class="chosen" tabIndex='0'
data-bind="
value:selectedParty,
options:availableParties,
optionsText:'name',
optionsValue:'id',
optionsCaption: 'Choose a company...',
chosen: { 'width' : '155px', 'search_contains' : true }">
</select>
<br><br>
<label>Extend until</label><br>
<input type="text" class="dp" data-bind="datepicker: selectedDate, datepickerOptions : { 'dateFormat' : 'yy-mm-dd' }">
<br><br>
<button data-bind="click:showSelection">Extend Trial</button>
CSS
body {
font-size:9pt;
font-family:segoe ui light;
}
.dp {
width:150px;
}
JavaScript
//custom ko binding for datepicker
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
}
};
//custom ko binding for chosen
ko.bindingHandlers.chosen =
{
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
{
var allBindings = allBindingsAccessor();
$(element).addClass('chzn-select');
$(element).chosen(allBindings.chosen);
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
{
$(element).trigger('chosen:updated');
}
};
window.viewBag = window.viewBag || {};
$(function() {
viewBag.parties = [];
viewBag.viewModel = {
selectedParty : ko.observable(undefined), //change undefined to 1 to test binding
selectedDate : ko.observable(),
availableParties: ko.observableArray(viewBag.parties),
showSelection : function() {
var selected = _.filter(viewBag.parties, function(n) {
return n.id == viewBag.viewModel.selectedParty(); });
if (selected.length > 0) {
alert(selected[0].name + ' ' + viewBag.viewModel.selectedDate());
}
}
};
ko.applyBindings(viewBag.viewModel);
var data = {
json: JSON.stringify({
selectedParty : 3,
availableParties: [
{ id: 1, name: 'ABC Pty Ltd' },
...