JSFiddle - React, Tailwind, and code Playground
by neonms92
HTML
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<select data-bind="options: theOptions, value: theValue, optionsText: formatDate"></select>
<br/>
<span data-bind="text: selectedIndex"></span>
<span> - </span>
<span data-bind="text: formatDate(theValue())"></span>
<br/>
<button data-bind="event: { click: resetOptions }">Reset Options</button>
<button data-bind="event: { click: removeSecond }">Remove Second</button>
<button data-bind="event: { click: setValue }">Set Value</button>
<button data-bind="event: { click: setValueToSecond }">Set value to Second</button>
<button data-bind="event: { click: selectSecond }">Select Second</button>
CSS
button {
display:block;
}
JavaScript
ko.extenders.alwaysContains = alwaysContains;
ko.extenders.cancellable = cancellable;
debugger;
function Model() {
var self = this;
// The Solution
var def = new Date();
self.theValue = ko.observable();
self.theOptions = ko.observable([]).extend({ alwaysContains: def });
// Functions, formats, and other stuff to make problem easier to solve
self.formatDate = function(d) {
if (d) return moment(d).format('YYYY-MM-DD');
}
self.selectedIndex = ko.computed(function() {
return self.theOptions().indexOf(self.theValue());
});
self.resetOptions = function() {
self.theOptions([
moment().startOf('day').toDate(),
moment().startOf('day').add('day',1).toDate(),
moment().startOf('day').add('day',2).toDate()
]);
if (!self.theValue()) self.theValue(self.theOptions()[1]);
}
self.removeSecond = function() {
var r = self.theOptions();
r.splice(1,1);
self.theOptions(r);
}
self.setValue = function() {
self.theValue(moment().startOf('day').toDate());
}
self.setValueToSecond = function() {
self.theValue(moment(self.theOptions()[1]).toDate());
}
self.selectSecond = function() {
self.theValue(self.theOptions()[1]);
}
}
window.model = new Model();
ko.applyBindings(model);
function alwaysContains(target, content) {
// Ensures that the target always contains something equal to the content.
// cancellable is an internal observable that allows us to cancel any changes made. (when it would be a result that doesn't contain content().)
// result is a simple computed that allows us to save a copy of whatever list the consumer has set to lastSetValue
// we only add the content value to lastSetValue. This means that when content changes, the old content item is removed.
var lastSetValue = target();
var cancellable;
var findIndex = function (arr, value) {
for (var i = 0; i <...