0

我有一个绑定到我的 html 的视图模型:

function ViewModel(height, color, replies, hasMissingReplies) {
  this.height = height + "%"; 
}

现在我的布局已正确显示,但我还使用 ViewModel 进行了一些计算,其中我总结了导致 NaN(不是数字)的高度,因为高度是一个字符串。

只有当我删除 %-char 时,我才有一个整数......但随后它被从 html 解释为像素,所以我的布局是错误的。

我可以使用对淘汰赛有什么帮助吗?

4

1 回答 1

0

有很多方法可以解决这个问题,但可能最简单的方法是:

function ViewModel(height, color, replies, hasMissingReplies) {
    this.height = +height; 
    this.heightString = this.height + "%";
}

只需保留两份!

如果你想要一个更“淘汰”的解决方案,你可以使用computedobservables:

function ViewModel(height, color, replies, hasMissingReplies) {
    var self = this;
    this.height = ko.observable(+height); 
    this.heightString = ko.computed(function() {
        return self.height() + "%";
    });
}    

但是,除非你需要你的height财产是可观察的,否则我真的不明白这一点。

于 2013-07-03T14:49:55.947 回答