jmogera jmogera - 1 year ago 123
Javascript Question

knockout.js subscribe is not getting called on the first set

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.

Answer Source

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
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download