dgaviola
dgaviola

Reputation: 2469

Knockout observable latest value

I'm wondering where Knockout stores value of observables. For example, I have the following code:

var field1 = ko.observable('a');
field1(); // prints 'a'
field1.peek(); // prints 'a'
field1._latestValue; //prints 'a'

field1._latestValuu = 'b';
field1._latestValue; //prints 'b'
field1(); // prints 'a'
field1.peek(); //prints 'a'

So not sure where Knockout stores value. I see the implementation of peek() and it returns _latestValue. However, even after manually changing _latestValue, I still get the old value when calling peek().

I would expect that, after I manually set _latestValue, calls like field1() or field1.peek() return the new value.

I know subscribers won't be called and that this might be a bit tricky as _latestValue is an internal variable, but that's fine for the problem I need to solve.

EDIT: the reason I want to do it is to set an initial value for a computed observable. So I want to be able to modify its _latestValue so when I call field() or field.peek() it returns the value I manually set instead of the calculated one. I will enable calculating with a flag, something like this:

var Object1 = function() {
    self.mode = ko.observable('read-only');
    self.calculated = ko.computed({
        read: function() {
           if (self.mode() == 'read-only') {
              if (self.calculated)
                  return self.calculated._latestValue;
           } else {
              // calculation goes here
           }
       },
       write: function(value) {
           self.calculated._latestValue = value;
       }
   });
};
var obj1 = new Object1();
obj1.calculated('a');
obj1.calculated(); // prints 'a'
obj1.mode('edit');
obj1.calculated(); // prints calculated value

Upvotes: 0

Views: 5969

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

There is an internal variable called _latestValue. In the debug build, this is exposed off of the observable as ._latestValue. However, setting it directly would not affect the internal _latestValue variable.

Like:

var a = 1
this.a = a;

this.a = 2;

In this sample, the variable a would still be 1;

Upvotes: 1

Related Questions