I am experimenting a bit with different ways to add methods to knockout viewmodels, and I came across an error I really don't understand.
function ViewModel() {
var self = this;
self.foo = ko.observable(null);
self.hasFoo = koputed(self.getHasFoo);
}
ko.utils.extend(ViewModel.prototype, {
getHasFoo: function () {
return this.foo() != null;
},
});
var vm = new ViewModel();
When I run this, I get an error saying Uncaught TypeError: this.foo is not a function
. I did a console.log on the actual value of this.foo, and it was indeed undefined
. I really don't understand why. What is going on here?
I am experimenting a bit with different ways to add methods to knockout viewmodels, and I came across an error I really don't understand.
function ViewModel() {
var self = this;
self.foo = ko.observable(null);
self.hasFoo = ko.puted(self.getHasFoo);
}
ko.utils.extend(ViewModel.prototype, {
getHasFoo: function () {
return this.foo() != null;
},
});
var vm = new ViewModel();
When I run this, I get an error saying Uncaught TypeError: this.foo is not a function
. I did a console.log on the actual value of this.foo, and it was indeed undefined
. I really don't understand why. What is going on here?
1 Answer
Reset to default 2That's because the context of the puted, this is the syntax ko.puted(handler,scope)
see the update this.hasFoo = ko.puted(self.getHasFoo,this);
, so now see it working in the snippet.
function ViewModel() {
var self = this;
this.foo = ko.observable(null);
this.hasFoo = ko.puted(self.getHasFoo,this);
}
ko.utils.extend(ViewModel.prototype, {
getHasFoo: function () {
return this.foo();
},
});
var vm = new ViewModel();
ko.applyBindings(vm)
<script src="https://cdnjs.cloudflare./ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="text" data-bind="textInput: foo"/>
<span data-bind="visible: hasFoo"> Has FOO!! </span>
Managing ‘this’
The second parameter to ko.puted (the bit where we passed this in the above example) defines the value of this when evaluating the puted observable. Without passing it in, it would not have been possible to refer to this.firstName() or this.lastName(). Experienced JavaScript coders will regard this as obvious, but if you’re still getting to know JavaScript it might seem strange. (Languages like C# and Java never expect the programmer to set a value for this, but JavaScript does, because its functions themselves aren’t part of any object by default.)
Ref. KO puted observables