使Knockout applyBindings将选择选项视为数字 [英] Make Knockout applyBindings to treat select options as number

查看:94
本文介绍了使Knockout applyBindings将选择选项视为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Knockout结合html选择/选项(请参阅小提琴):

Im using Knockout in combination with html select / option (see Fiddle):

<select data-bind="value: Width">
    <option>10</option>
    <option>100</option>
</select>

当调用 applyBindings 时,这个选项被视为字符串。这导致不希望的影响。考虑下面的示例:

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);
});

当调用 applyBindings 时, self.Width self.Height 从它们的初始值10到10进行了类型化,这导致了对所计算函数的重新评估。

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.

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

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?

推荐答案

您可以将宽度设置为计算值,然后编写自己的写入和读取选项:

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));
     }
  }

这篇关于使Knockout applyBindings将选择选项视为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆