Joep Geevers
Joep Geevers

Reputation: 585

Why can't I access my viewmodel from within a computed property?

For a single-page application I need to use multiple ViewModels at the same time, but can't seem to access a different ViewModel from within a computed property of another.

An (extremely simplified) example is: (http://jsfiddle.net/5t2tb/14/)

html:

<div data-bind="foreach: Search.results">
    <a data-bind="text: id, css: { IsInBookshelf: IsInBookshelf() }"></a>
</div>

javascript:

var ViewModels = {
    Search: new SearchViewModel()
};

function SearchViewModel() {
    this.results = ko.observableArray([new Book(123), new Book(456)]);
}

function Book(id) {
    this.id = ko.observable(id);

    this.IsInBookshelf = ko.computed(function () {
        alert(ViewModels);
        return id%2==0;
    }, this);
}

ko.applyBindings(ViewModels);

style

.IsInBookshelf {
    background-color: yellow;
}

I can't figure out why var ViewModels in computed method IsInBookshelf is undefined, as it is supposed to be a global variable.

Upvotes: 1

Views: 1107

Answers (1)

go-oleg
go-oleg

Reputation: 19480

Thats because at the time that ko.computed is being executed (as part of new Book as part of new SearchViewModel), the value has not yet been assigned to ViewModels since its still being "executed". If you need to have a reference to ViewModels in your computed observable, you can create the ViewModels object and then set the Search property separately:

var ViewModels = {};
ViewModels.Search = new SearchViewModel();

new fiddle

Note that at ViewModel.Search creation time, ViewModels will not have a Search property, but when the ko.computed is triggered at a later point, it will.

Upvotes: 3

Related Questions