Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS Inheriting functionality via ko.utils.extend

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.

like image 408
Cameron Askew Avatar asked Dec 04 '13 00:12

Cameron Askew


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";
}
like image 134
Cameron Askew Avatar answered Nov 02 '22 23:11

Cameron Askew


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.

like image 28
RP Niemeyer Avatar answered Nov 02 '22 23:11

RP Niemeyer