Search code examples
javascriptknockout.jsknockout-3.0

Force to ko.observable manually to notify subscribscription on page load


I'm trying to trigger self.selectedNavigation subscription each time my page loads. I have tried the code below, but it is not working.

self.selectedNavigation = ko.observable(-1);
self.selectedNavigation.extend({ notify: 'always' });
self.selectedNavigation(self.navigations()[0].id());
self.selectedNavigation.valueHasMutated();

self.selectedNavigation.subscribe(function (newValue) {
    alert(newValue);
});

Is this even possible? if yes, how do I trigger it?


Solution

  • For a subscription to get notified for changes, it has to be registered before the actual change has occurred:

    // first defining the observable
    self.selectedNavigation = ko.observable(-1);
    
    // subscribing for changes
    self.selectedNavigation.subscribe(function(newValue) {
        alert(newValue);
    });
    
    // mutating value
    self.selectedNavigation(1);
    

    See Fiddle