I'm trying to inherit functionality from a parent view model to a child view model like so:
function ParentVM() {
var self = this;
self.MyFunc = function () {
console.log(self.SomeVar); // this logs "undefined"
}
}
function ChildVM() {
var self = this;
ko.utils.extend(self, new ParentVM());
self.SomeVar = "hello";
}
However, when MyFunc is called, SomeVar is undefined.
In case anybody is struggling with this, I found a solution outside of the KnockoutJS framework:
function ParentVM() {
var self = this;
self.MyFunc = function () {
console.log(self.SomeVar);
}
}
function ChildVM() {
var self = this;
ParentVM.apply(self); // this instead
self.SomeVar = "hello";
}
you would want to use this instead of self in MyFunc. The way it is written now, MyFunc will always use self that is set to the value of this that is the new ParentVM instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With