JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://github.com/jquery/jquery-tmpl/raw/master/jquery.tmpl.js"></script>
<script src="https://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.debug.js"></script>
<div data-bind="template: 'monthInfoTemplate'" />
<script type="text/html" id="monthInfoTemplate">
<span data-bind="text:Name, style:{color:SecurityCode().value}"></span>
<select data-bind="options:Code, optionsText: 'name', value:SecurityCode" />
<button data-bind="click:function(){undoService.undo()}">Undo</button>
<button data-bind="click:function(){undoService.redo()}">Redo</button>
</script>
JavaScript
var UndoService = function() {
this.stack = [];
this.position = 0;
function add(undoItem) {
this.stack.push(undoItem);
this.redo();
}
function undo() {
if (this.position != 0) {
this.position--;
this.stack[this.position].undo();
}
}
function redo() {
if ((this.stack.length !== 0) && (this.position < this.stack.length)) {
this.stack[this.position].redo();
this.position++;
}
}
this.add = add;
this.undo = undo;
this.redo = redo;
};
var UndoItem = function(observable, oldValue, newValue) {
this.item = observable;
this.oldValue = oldValue;
this.newValue = newValue;
function undo() {
this.item(this.oldValue);
}
function redo() {
this.item(this.newValue);
}
this.undo = undo;
this.redo = redo;
};
ko.protectedObservable = function(initialValue) {
var _actualValue = ko.observable(initialValue);
var _tempValue = initialValue;
var result = ko.dependentObservable({
read: function() {
return _actualValue();
},
write: function(newValue) {
var undoItem = new UndoItem(_actualValue, _tempValue, newValue);
undoService.add(undoItem);
}
});
return result;
};
var Code = [
{
name: 'Severe',
value: 'Red'},
{
name: 'High',
value: 'Orange'},
{
name: 'Elevated',
value: 'Yellow'},
{
name: 'Guarded',
value: 'Blue'},
{
name: 'Low',
value: 'Green'},
];
var MonthInformation = function() {
this.Name = "";
this.SecurityCode = Code[0];
};
var undoService = new UndoService();
var jan2011 = new MonthInformation();
jan2011.Name = "January";
jan2011.SecurityCode = ko.protectedObservable(Code[4]);
ko.applyBindings(jan2011);