我试图了解如何管理 Javascript 代码中的范围。创建 View 模型后,如何从 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;
最佳答案
ko.observable 是一个函数,因此要引用可观察值,您必须有小括号
例如从上面的例子
var test = AppViewModel.gridSize();
发现这个很好的解释 http://knockoutjs.com/documentation/observables.html
关于javascript - 如何从 javascript 访问 knockout View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413765/