Lai32290
Lai32290

Reputation: 8548

How to select parent view model in Knockout?

I using two view models, mainViewModel and filterViewModel in my page, where filterViewModel is instanced by mainViewModel

function mainViewModel() {
    this.data   = ko.observableArray();
    this.filter = new filterViewModel();
}

function filterViewModel() {
    this.filter = function() {
        // ajax blablabla
    }
}

How to can I access my mainViewModel from filterViewModel for set ajax result, executed by filterViewModel, to data variable in your parent view model?

Upvotes: 2

Views: 1474

Answers (1)

uKolka
uKolka

Reputation: 38680

Just pass the parent to the child explicitly for simplicity sake.

function mainViewModel() {
    this.data   = ko.observableArray();
    this.filter = new filterViewModel(this);
}

function filterViewModel(parent) {
    // do whatever with the parent
    this.filter = function() {
        // ajax blablabla
    }
}

As comments point out that is introducing an unnecessary dependency. So it's better to pass the property you want to use instead of the parent model.

function mainViewModel() {
    this.data   = ko.observableArray();
    this.filter = new filterViewModel(this.data);
}

function filterViewModel(data) {
    // do whatever with the data
    this.filter = function() {
        // ajax blablabla
    }
}

Or you could use an awesome knockout plugin knockout-postbox

function mainViewModel() {
    this.data = ko.observableArray()
         .syncWith('parentData');
    this.filter = new filterViewModel();
}

function filterViewModel() {
    this.parentData = ko.observableArray()
        .syncWith('parentData');

    this.filter = function() {
        // ajax blablabla
        // do whatever with this.parentData
    }
}

Note that "parentData" could be any unique string that identifies the property of the model of your choice.

Upvotes: 5

Related Questions