我正在玩 Knockout JS,在这个代码示例中:
var data =
{
allMakes: ko.observableArray([
{ name: "Toyota" },
{ name: "Fiat"}
]),
allModels: ko.observableArray([
{ name: "Corolla", make: "Toyota" },
{ name: "Celica", make: "Toyota" },
{ name: "Avensis", make: "Toyota" },
{ name: "Uno", make: "Fiat" },
{ name: "Bravo", make: "Fiat" }
])
};
var myViewModel =
{
makes : data.allMakes,
models: ko.computed(function() {
if (!myViewModel.selectedMake())
return;
// TODO: filter models by selected make
}),
selectedModel: ko.observable(""),
selectedMake: ko.observable("")
};
/* Uncomment it to work
myViewModel.models = ko.computed(function() {
if (!myViewModel.selectedMake())
return;
// TODO: filter models by selected make
});
*/
ko.applyBindings(myViewModel);
http://jsbin.com/upaxum/8/edit
我们可以看到我尝试访问模型中的myViewModel变量: ko.computed 。然而,当这个计算的 observable 运行时 myViewModel 是未定义的。我不知道为什么?
但是,如果我在下一条语句中创建可观察到的计算模型,则会定义myViewModel变量。这是为什么?
编辑:其中一个答案表明我在创建对象之前正在访问它。那么这个代码片段是如何工作的呢?
var myViewModel =
{
myFnk : function()
{
console.log(myViewModel);
}
};
myViewModel.myFnk();