2013-04-17 65 views
3

采用淘汰赛即时通讯与HTML组合选择/选项(参见Fiddle):使淘汰赛applyBindings治疗选择的选项数量

<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调用。

哪个(花哨的)解决方案可以解决这个问题?

+1

结帐http://stackoverflow.com/questions/7395946/knockout-js-json-has-numeric-but-knockout-changes-it-to-string-any-suggestions – Luffy

+0

是的,那就是我错过的。谢谢。 – Dresel

回答

1

可以使宽度计算,写自己的“写”和“读”这样的选项:

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

我会坚持推荐你的建议(类似于http://stackoverflow.com/a/7396039/1249506)。谢谢。 – Dresel

2

你可以尝试像

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

这对我有用。干杯。 – Aeptitude