I’m looking through the knockout tutorials, and all the examples create the view model using the ‘new’ keyword:
//from learn.knockoutjs.com
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
}
ko.applyBindings(new AppViewModel());
I’m trying to avoid using the new keyword, which usually works perfectly ok, but I find trouble getting the fullName computed property to work. This is what I’ve come up with so far.
function makeViewModel() {
return {
firstName: ko.observable("Bert"),
lastName: ko.observable("Bertington"),
fullName: ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this) };
}
ko.applyBindings(makeViewModel());
…which obviously fails since ‘this’ no longer refers to the local object inside the function passed to computed. I could get around this by creating a variable and store the view model before attaching the computed function and returning it, but if there exists a more elegant and compact solution that doesn’t require me to make sure that methods that depend on each other are attached in the correct order, I’d sure like to use that instead.
Is there a better solution?
When creating it in a function, it is not necessary to return a new object. Instead you would do:
Now you have access to the proper this in the computed observable.
If you really do not want to use “new” (there is no reason why you should not in this case), then you could do something like: