Reputation: 1541
I'm using a sample project (durandal541) for reference in adding authentication to my durandal-based app. In it I notice in the viewmodel for most of the pages, the programmer has done this:
// Reveal the bindable properties and functions
var vm = {
activate: activate,
goBack: goBack,
title: 'manage',
session: session,
userName: ko.observable(),
logins: ko.observableArray(),
localLoginProvider: ko.observable(),
externalLoginProviders: ko.observableArray(),
message: ko.observable()
};
vm.hasLocalPassword = ko.computed(function () {
var logins = vm.logins();
for (var i = 0; i < logins.length; i++) {
if (logins[i].loginProvider() === vm.localLoginProvider()) {
return true;
}
}
return false;
});
vm.changePassword = ko.computed(function () {
if (!vm.hasLocalPassword()) {
return null;
}
return new ChangePasswordViewModel(vm, vm.userName());
});
...
What is the point/benefit in adding "hasLocalPassword" and "changePassword" to the just-defined "vm" viewmodel rather than doing this, where they are included as part of the viewmodel at definition?:
// Reveal the bindable properties and functions
var vm = {
activate: activate,
goBack: goBack,
title: 'manage',
session: session,
userName: ko.observable(),
logins: ko.observableArray(),
localLoginProvider: ko.observable(),
externalLoginProviders: ko.observableArray(),
message: ko.observable(),
hasLocalPassword = ko.computed(function () {
var logins = vm.logins();
for (var i = 0; i < logins.length; i++) {
if (logins[i].loginProvider() === vm.localLoginProvider()) {
return true;
}
}
return false;
}),
changePassword = ko.computed(function () {
if (!vm.hasLocalPassword()) {
return null;
}
return new ChangePasswordViewModel(vm, vm.userName());
})
};
Upvotes: 1
Views: 38
Reputation: 1541
Ah. Now I see. As explained at 10:45 in this video by Ryan Niemayer! http://vimeo.com/51103092
This question will probably be deleted, but just in case any other noobs are wondering - the simple answer is that ko.computeds are evaluated immediately (unless you add in the deferred option of course) and this means that any computed that refers to the "vm" viewmodel in this case would fail on startup if defined within the viewmodel itself (as per my second example) because vm simply DOES NOT EXIST at that moment! Hence adding the computeds to the defined viewmodel object AFTER initial definition as in the first example.
Upvotes: 2