我将 Knockout 与 html 选择/选项结合使用(请参阅 Fiddle):
<select data-bind="value: Width">
<option>10</option>
<option>100</option>
</select>
调用 applyBindings
时,此选项被视为字符串。这会导致不良影响。考虑以下示例:
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);
});
当 applyBindings
被调用时,self.Width
和 self.Height
被从它们的初始值 10 类型转换为“10”,这导致重新评估计算函数。
这在这里似乎没什么大不了的,但在更复杂的解决方案中,我有一个 PageSize 属性(每页 100/500/1000 行),当此属性更改时会导致多次 AJAX 调用。
有哪些(奇特的)解决方案可以解决这个问题?
最佳答案
你可以尝试类似的东西
self.Width = ko.observable(10);
self.Width.subscribe(function(newValue){
if(typeof newValue === "string"){
self.Width(parseInt(newValue));
}
});
关于javascript - 使 Knockout applyBindings 将选择选项视为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16056103/