Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Knockout applyBindings to treat select options as number

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?

like image 296
Dresel Avatar asked Oct 21 '25 04:10

Dresel


2 Answers

You can try something like

self.Width = ko.observable(10);
self.Width.subscribe(function(newValue){
   if(typeof newValue === "string"){
       self.Width(parseInt(newValue));
   }
});
like image 107
demkalkov Avatar answered Oct 22 '25 19:10

demkalkov


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));
     }
  }
like image 43
SiMet Avatar answered Oct 22 '25 18:10

SiMet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!