I have a viewmodel that's a created by a constructor function, with a bunch of observable properties and a bunch of plain old properties. Once I instantiate it, if I set a value on the instance, the change to that value doesn't get reflected in the computed observable.
Here's a distilled version of what I'm looking at:
function ViewModel(active) {
var self = this;
self.active = active;
self.getClasses = ko.computed(function () {
return this.active ? "yup" : "nope";
}, self);
}
var vm = new ViewModel(false);
vm.active = true;
alert(vm.getClasses()); //returns "nope" :/
This computed observable will re-evaluate if I touch an observable it depends on, but calling it directly results in evaluation with the old value of active.
Does the ko.computed create a new closure that ignores updates to the parent? Is it ill-advised to mix plain values with observable ones? (The computed I'm actually having a problem with has dependencies on observables and on other properties, but I don't expect the other properties to change at runtime. This is only actually a problem in my unit tests right now.)
I can certainly make active an observable, but I'm wondering if there's another way to do this.
self.active = ko.observable(active);or don't use a computed here but a regular function:self.getClasses = function () { return self.active ? "yup" : "nope"; };For further read: knockoutjs.com/documentation/computedObservables.html How dependency tracking works section - nemesvko.computedworks. The evaluator function only invoked intially and only if a dependent observable changed. You cannot tell a computed to updated its value. So don't use computed here. - nemesv