KnockoutJS Inheriting functionality via ko.utils.extend

Viewed 3857

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.

2 Answers

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.

Related