1

我试图了解如何在我的 Javascript 代码中管理范围。一旦我创建了一个视图模型,我如何从我的 javascript 的其余部分访问它?(此代码的最后一行会生成“未定义”错误

注意:我发现了几篇关于 ko 的 function/var 之间差异的帖子,但没有人说使用 var 有范围优势......所以我尝试了这两种方法。

//function AppViewModel() {
//    this.gridSize = ko.observable("30");
//    this.canvasWidth = ko.observable("600");
//    this.canvasHeight = ko.observable("600");
//    this.displayCoords = "Axial";
//    this.pixel="0";
//    this.hex="0";
//}
//ko.applyBindings(new AppViewModel());

var AppViewModel = {
    gridSize: ko.observable("30"),
    canvasWidth: ko.observable("600"),
    canvasHeight: ko.observable("600"),
    displayCoords: "Axial",
    pixel:"0",
    hex:"0"
};
ko.applyBindings(AppViewModel );

var test = AppViewModel.gridSize;
4

1 回答 1

1

ko.observable 是一个函数,因此要引用一个可观察的值,你必须有括号

例如从上面的例子

var test = AppViewModel.gridSize();

找到了这个很好的解释 http://knockoutjs.com/documentation/observables.html

于 2013-08-24T05:48:19.637 回答