This is something that trips me up from time to time. ko.computed executes once as soon as it is defined. It does this so that it knows which variables it needs to subscribe to watch for changes.
So in this code
models: ko.computed(function() {
if (!myViewModel.selectedMake())
return;
// TODO: filter models by selected make
})
myViewModel is accessed before it has been assigned to in the var myViewModel =
line because the ko.computed is executing the function as soon as it is defined.
In your second example you are executing the function AFTER myViewModel has been defined so that is why it works. If you wanted to replicate this in your first example you might do something like:
var myViewModel =
{
makes : data.allMakes,
selectedModel: ko.observable(""),
selectedMake: ko.observable("")
};
myViewModel.models = ko.computed(function() {
if (!myViewModel.selectedMake())
return;
// TODO: filter models by selected make
});