0
votes

I have a problem with my knockout implementation. I am new to knockout so would appreciate the help.

I have the following code:

    function updateViewModel() {
        if (typeof groupId == 'undefined') {
            groupId = getDefaultGroupId();
        }

        $.getJSON("api/livestatusgroup/children/" + groupId)
            .done(function (data) {
                ko.mapping.fromJS(data, liveStatusViewModel.groups);
                groupsLoaded();
            });

        $.getJSON("api/livestatusgroup/resources/" + groupId)
            .done(function(data) {
                ko.mapping.fromJS(data, liveStatusViewModel.resources);
                resourcesLoaded();
            });

        this.resourceImagePath = ko.computed(function () {
            return "../Image/" + this.ResID;
        }, this);
    }


    function ViewModel() {
        var self = this;
        self.resources = ko.mapping.fromJS([]);
        self.groups = ko.mapping.fromJS([]);
    }

    var vm = new ViewModel();
    ko.applyBindings(vm);

Unfortunately, the computed observable function resourceImagePath is not correctly capturing the ResID for my resource, so I end up with urls like /Image/undefined.

What am I missing? I have checked and the ResID field definitely exists in the view model.

S

1
1. It's not clear, how do you call updateViewModel() function (what object this refers to?). 2. Anyway your computed wouldn't work whis way, because it's not subscribed to ResID, regardles is it observable or not. - ataman
So, please show us full code of model, containing ResID, and the code where you call updateViewModel(). - ataman

1 Answers

0
votes

When you implement a ko.computed observable, it only creates a dependency for observables that are referenced within the computed function. Remember that observables must be referenced by executing them, because they are functions - it's this action that allows the computed function to detect and track a dependency.

Otherwise, the computed function will only be able to use the value that is available at the time the computed function is first executed.

This code references this.ResID, but doesn't have any dependency on it due to not treating ResID as an observable.

 this.resourceImagePath = ko.computed(function () {
        return "../Image/" + this.ResID;
    }, this);

Try ensuring that this.ResID is, in fact, an observable, and add parentheses like this:

 this.resourceImagePath = ko.computed(function () {
        return "../Image/" + this.ResID();
    }, this);