Search code examples
knockout.jsknockout-3.0

How to find all the subscriptions functions from an observable while debugging


I am debugging through my knockout application. While debugging I change some observable value like

data.myObservable(true);

where data is passed to my function.

At this point when I analyze the variable using the scope in developer console I see that there are 3 subscriptions registered to this variable.

Is there any way to find the locations of these subscriptions methods.


Solution

  • Since it's only for debugging purposes, you could use the private _subscriptions property on a subscribable.

    Here's an example:

    const myObs = ko.observable();
    
    const cb1 = function(newVal) { };
    const cb2 = function(newVal) { };
    const cb3 = function(newVal) { };
    
    myObs.subscribe(cb1);
    myObs.subscribe(cb2);
    myObs.subscribe(cb3);
    
    myObs(10);
    
    console.log(
      "There are",
      myObs.getSubscriptionsCount(),
      "subscribers to `myObs`:",
      myObs._subscriptions.change.map(
        ({ callback: { name }}) => name
      ).join(", ")
    
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-debug.js"></script>

    Of course you can also put a breakpoint in the line that sets the observable and then use "step in to" to go through the function calls. If you "blackbox" knockout.js in your debugger, it should take you directly to the first subscribed method.