The Template.onSubscribed() callback


#1

Template-level subscriptions are great, but how do you know when they’re done loading? What if there was a way to execute a callback once all your data is there?

Well, now there is thanks to a super-simple little package I just created:

https://atmospherejs.com/utilities/onsubscribed

Template.myTemplate.onCreated(function () {
  this.subscribe("mySubscription");
});

Template.myTemplate.onSubscribed(function () {
  console.log("subscription done!");
});

#2

Does it only fire once? Or if I make additional subscriptions will it fire again?


#3

Right now it only fires once:

Template.prototype.onSubscribed = function(callback) {
  var template = this;
   template.onCreated(function() {
      var templateInstance = this;
      templateInstance.autorun(function(computation) {
         if (templateInstance.subscriptionsReady()) {
            callback.bind(templateInstance)();
            computation.stop();
         }
      });
   });
};

But I guess we could just not stop the computation, and it would reactively fire every time subscriptionsReady() changes?


#4

Hey! That looks alot like what I’m doing by hand atm.

    Tracker.autorun(function () {
        // wait for startup to be ready before running this code
        if (!Mk.Subs.startup.ready()) return;
        Tracker.currentComputation.stop();

        self.subscribe('organisation', lastMsg.organisationId, {
            onReady: function () {...}
        });
    })

That first line though is because if a user starts on a certain page, I have global subscriptions that need to finish as well as the template level subscription. So I put that in to wait for both global level subscriptions and template level ones!

What I’d want to see is:

var subHandle = Template.instance().subscribe(...) || Meteor.subscribe(...)
Meteor.onReady(subHandle, function () {
});

It would be good to be able to use this in templates or outside of them. Not sure if these two methods of subscription can be combined.


#5

Yeah, I would love for it to be easier to use template-level subscriptions in combination with SubsManager cached subscriptions or any other global subscriptions.

So it’d be great if there was an easy syntax to build a handler that waits for any number of subscriptions.