Make Knockout applyBindings to treat select option

2019-07-04 23:02发布

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?

2条回答
Melony?
2楼-- · 2019-07-04 23:24

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));
     }
  }
查看更多
三岁会撩人
3楼-- · 2019-07-04 23:29

You can try something like

self.Width = ko.observable(10);
self.Width.subscribe(function(newValue){
   if(typeof newValue === "string"){
       self.Width(parseInt(newValue));
   }
});
查看更多
登录 后发表回答