5

I have a simple model class with observables. I simply want to subscribe to its sets. Here is the code that I have:

var dto = function (data) {
    var self = this;
    self.Value1 = ko.observable(data.Value1);
    self.Value1.subscribe(function(){
         console.log('here');
    });   
};

the console.log doesn't get called when the Value1 is first set (i.e. ko.observable(data.Value1)

How do I set it up that subsribe function happens on both initial and when it changes.

4

4 回答 4

14

There is no real support for triggering the subscribe function for the initial values.

What you can do is to call the valueHasMutated function after your subscribe:

self.Value1.subscribe(function(){
     console.log('here');
}); 
self.Value1.valueHasMutated();

Or you can just set your initial values after you've subscribed:

var dto = function (data) {
    var self = this;
    self.Value1 = ko.observable(); // only declare but not assign
    self.Value1.subscribe(function(){
         console.log('here');
    });   
    self.Value1(data.Value1); // assign initial value
};
于 2014-01-02T07:30:59.640 回答
1

To improve a bit on richard's answer. If this is a recurring situation, where you don't know if an observable has gotten a value already but you want to call the subscriber if it has, then you can extend the KO subscribable with this function that has the same signature as the original subscribe:

ko.subscribable.fn.subscribeAndCall = function(subscribingFunction, context, event) {
  var subscribableValue = this();

  this.subscribe(subscribingFunction, context, event);

  if (subscribableValue !== undefined) {
    subscribingFunction.call(context, subscribableValue);
  }
};

It also works for initial values that are falsy and will not accidentally trigger any other subscribers of the observable.

Example usage for the original question:

self.Value1.subscribeAndCall(function(){
     console.log('here');
}, this);
于 2017-02-07T16:05:59.717 回答
0

I think subsribe function does not ment to work like that. In other words you use it when you to execute some callback/logic when your observable object has changed.

From @RP Niemeyer answer here:

To notify subscribers that they should re-evaluate, you can use valueHasMutated() on you observable object

于 2014-01-02T10:30:49.163 回答
0

I just write this for my own use:

koSubscribe = function(observable, callback){
    observable.subscribe( callback );

    if (observable()) {
        observable.valueHasMutated();
    }
}

It is based on other answers here. But fixes the problem of “what if it has not been set yet?” So this should work as long as the observable exists.

usage: koSubscribe(value1, function() {…}); where value1 is a ko.observable.

于 2014-03-31T13:20:05.883 回答