未调用计算函数

时间:2014-06-20 14:12:00

标签: knockout.js

我有以下视图模型

var viewModel = {
FLFSExamIsH: ko.observable(true),
FLFSROIEntryFieldDynPosBottom: ko.computed(function() {
    return this.FLFSExamIsH ? "flfs_ROIImagesRow3Pos" : "flfs_ROIImagesRow2Pos";
}),

};

在我的html页面中,我按如下方式绑定div:

data-bind='css: FLFSROIEntryFieldDynPosBottom'

在我的代码中的某个时刻,我执行:viewModel.FLFSExamIsH(false);

但是在任何时候(在chrome调试器中)viewModel.FLFSROIEntryFieldDynPosBottom()总是返回'flfs_ROIImagesRow2Pos',无论对viewmodel的更新如何:viewModel.FLFSExamIsH()

在计算函数上设置断点并更新该模型变量也不会重新计算计算函数。

2 个答案:

答案 0 :(得分:3)

缺少括号
return this.FLFSExamIsH ? "flfs_ROIImagesRow3Pos" : "flfs_ROIImagesRow2Pos";
//                    ^^^ here, it should be this.FLFSExamIsH()

另外,因为你没有使用函数来定义你的viewmodel,所以应该在之后添加计算结果(检查this thread以获取更多信息):

var viewModel = {
    FLFSExamIsH: ko.observable(true),
};
viewModel.FLFSROIEntryFieldDynPosBottom = ko.computed(function() {
    return this.FLFSExamIsH() 
                 ? "flfs_ROIImagesRow3Pos" 
                 : "flfs_ROIImagesRow2Pos";
});

<强> Demo

答案 1 :(得分:0)

如果您不使用函数构造函数,则无法使用this关键字。

相关问题