使Knockout applyBindings将选择选项视为数字

时间:2013-04-17 09:13:48

标签: javascript html knockout.js

我将Knockout与html select / option结合使用(参见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.Widthself.Height会从其初始值10到“10”进行类型转换,从而导致重新评估计算函数。

这在这里似乎不是什么大问题,但在更复杂的解决方案中,我有一个PageSize属性(每页100/500/1000行),这会在更改此属性时导致多个AJAX调用。

哪些(奇特的)解决方案可以解决这个问题?

2 个答案:

答案 0 :(得分:2)

您可以尝试类似

的内容
self.Width = ko.observable(10);
self.Width.subscribe(function(newValue){
   if(typeof newValue === "string"){
       self.Width(parseInt(newValue));
   }
});

答案 1 :(得分:1)

您可以将Width设置为计算并编写自己的“write”和“read”选项,如下所示:

var _width = ko.observable(10);
self.Width = ko.computed({
  read : function(){
     return _width;
  },
  write: function(value){
     if(typeof value === "string"){
        _width(parseInt(value));
     }
  }