BASE

by whelkaholism

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<ul data-bind="foreach: Log"><li data-bind="text: $data"></li></ul>

EV[<span data-bind="text: EditableValue"></span>]<br/>
V[<span data-bind="text: Value"></span>]<br/>
<select data-bind="value: EditableValue, options: Options, optionsValue: 'Key', optionsText: 'Value', valueAllowUnset: true"></select>

CSS

/*
*/

JavaScript

function Model(data, mapping)
{
    var _this = this;
    var _mapping = $.extend({}, {}, mapping);
    
   	this.Log = ko.observableArray([]);
    
    this.Options = ko.observableArray([
        { Key: 'ALL', Value: 'All' },    
        { Key: 'OPT1', Value: 'OPT1' },    
        { Key: 'OPT2', Value: 'OPT2' }
	]);
    
    this.Type = ko.observable('Select');
    this.Value = ko.observable('ALL');
    
	// Computed
	this.EditableValue = ko.computed({
		read:
			function()
			{                
				var res = '';
								
				if(_this.Type() == 'DateTime')
					res = _this.Value.dt();
				else
					res = _this.Value();
			
                _this.Log.push('read: ' + JSON.stringify(res));
                
				return res;
			},
		write:
			function(newval)
			{
                _this.Log.push('write: ' + JSON.stringify(newval));
                
				if(_this.Type() == 'DateTime')
					_this.Value.dt(newval);
				else
					_this.Value(newval);
			}			
	});
    
    if(data)
        ko.mapping.fromJS(data, _mapping, _this);
}

var model = new Model();
ko.applyBindings(model);