user1167777
user1167777

Reputation: 93

knockout computed dependency is empty initially

I have this viewmodel, on my web I have a dropdown that updates the sortedallemployees option. It works fine except my table is empty initially. Once I sort the first time I get data. Seems like when the vm is created it doesn't wait for allemployees to be populated.

var vm = {
   activate: activate,
   allemployees: allemployees,
   sortedallemployees:ko.computed( {
   return allemployees.sort(function(f,s) {
   var ID =  SelectedOptionID(); 
   var name = options[ ID - 1].OptionText;
        if (f[name] == s[name]) {
            return f[name] > s[name] ? 1 : f[name] < s[name] ? -1 : 0;
            }
           return f[name] > s[name] ? 1 : -1;

            });

}

Upvotes: 0

Views: 102

Answers (1)

Kyeotic
Kyeotic

Reputation: 19867

Without the rest of your code, its difficult to tell exactly how this will behave. That being said, you are doing several very odd things that I would recommend you avoid.

First, defining all but the simplest viewmodels as object literals will cause you pain. Anything with a function or a computed will almost certainly behave oddly, or more likely not at all, when defined this way.

I would recommend using a constructor function for your viewmodels.

var Viewmodel = function(activate, allEmployees) {
    var self = this;
    self.activate = activate;
    self.allEmployees = ko.observableArray(allEmployees);
    self.sortedEmployees = ko.computed(function() {
        return self.allEmployees().sort(function(f,s) {
            //your sort function
        });
    });
};

var vm = new Viewmodel(activate, allemployees);

This method has several advantages. First, it is reusable. Second, you can reference its properties properly during construction, such as during the computed definition. It is necessary for a computed to reference at least one observable property during definition for it to be reactive.

Your next problem is that your computed definition is not a function, but an object. It isn't even a legal object, it has a return in it. This code shouldn't even compile. This is just wrong. The Knockout Documentation is clear on this point: computed's are defined with a function.

Your last problem is that your sort function is referencing things outside the viewmodel: SelectedOptionID(). This won't necessarily stop it from working, but its generally bad practice.

Upvotes: 1

Related Questions