问题
Im using Knockout in combination with html select / option (see Fiddle):
<select data-bind="value: Width">
<option>10</option>
<option>100</option>
</select>
When calling applyBindings this options are treated as strings. This leads to unwanted effects. Consider the following Sample:
function AreaViewModel() {
var self = this;
self.Width = ko.observable(10);
self.Height = ko.observable(10);
self.Area = ko.computed(function () {
return self.Width() * self.Height();
});
}
$(document).ready(function () {
var viewModel = new AreaViewModel();
ko.applyBindings(viewModel);
});
When applyBindings is called, self.Width and self.Height are typecasted from their initial value 10 to "10", which leads to reevaluation of the computed function.
This doesn't seem to be a big deal here, but in a more complex solution I have an PageSize Property (100 / 500 / 1000 Row per Page) which results in multiple AJAX calls when this property is changed.
Which (fancy) solutions are there to overcome this problem?
回答1:
You can make Width as computed and write own "write" and "read" options like that:
var _width = ko.observable(10);
self.Width = ko.computed({
read : function(){
return _width;
},
write: function(value){
if(typeof value === "string"){
_width(parseInt(value));
}
}
回答2:
You can try something like
self.Width = ko.observable(10);
self.Width.subscribe(function(newValue){
if(typeof newValue === "string"){
self.Width(parseInt(newValue));
}
});
来源:https://stackoverflow.com/questions/16056103/make-knockout-applybindings-to-treat-select-options-as-number