Bind to float / numbers. ("") is added to json model #2
https://groups.google.com/forum/#!topic/knockoutjs/5WcUS2Od9NM
by PAEz
HTML
<script src="http://knockoutjs.com/js/jquery.tmpl.js"></script>
<script src="https://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.debug.js"></script>
<script src="http://jscolor.com/example/jscolor/jscolor.js"></script>
<label>Bad: </label>
<input data-bind="value: units" size="3" />
<span data-bind="text: ko.toJSON(units)"></span>
<hr/>
<label>Good: </label>
<input size="3" t data-bind="value: units2"/>
<span data-bind="text: ko.toJSON(units2)"></span>
<hr/>
Click here: <input class="color" data-bind="value: color">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" data-bind="height: units , style: { fill: color }"
style="fill:rgb(0,0,255);stroke-width:1;
stroke:rgb(0,0,0)"/>
<defs>
<linearGradient id="orange_red" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1"/>
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" data-bind="style: { stopColor: color }"/>
</linearGradient>
</defs>
<ellipse cx="200" cy="190" rx="85" ry="55"
style="fill:url(#orange_red)"/>
</svg>
JavaScript
ko.numericObservable = function(initialValue) {
var _actual = ko.observable(initialValue);
var result = ko.dependentObservable({
read: function() {
return _actual();
},
write: function(newValue) {
var parsedValue = parseFloat(newValue);
_actual(isNaN(parsedValue ) ? newValue: parsedValue);
}
});
return result;
};
var viewModel = {
units: ko.observable(250),
units2: ko.numericObservable(2.50),
color: ko.observable('FFFFFF')
};
ko.bindingHandlers['height'] = {
'update': function(element, valueAccessor) {
//$(element).hide();
// ko.bindingHandlers.text.update(element, valueAccessor);
// First get the latest data that we're bound to
var value = valueAccessor();
element.setAttribute('height',value());
}
};
ko.applyBindings(viewModel);