Can't call View#subscribe from inside the destroyed callback [Solved]


I got an error and strange behavior inside template.onDestoyed;

I have code for infinite scroll subscribtion (it stored in special subscribtion-template) It work fine, until i switch to another route, and create a new instance of subscriber-template.


  Template.subscriber.onCreated(function() {
        var template = this;
        var skipCount = 0;
        template.autorun(function(c) {
            template.subscribe(, skipCount,;
            var block = true;
            $(window).scroll(function() {
                if (($(window).scrollTop() + $(window).height()) >= ($(document).height()) && block) {
                    block = false;
                    skipCount = skipCount +;
                    console.log("skip_count is "+skipCount);
                    template.subscribe(, skipCount,, {
                        onReady: function() {
                            block = true;
                        onStop: function() {
                            console.log('route switched, subscribtion stopped');

When i “scroll down” on a page, subscriber work fine, when i go in another page and “scroll down” first i get a data from old subscriber template (what must be destroyed in theory) in first time. In second time (scroll down again) new instance of subscriber starts works normally.

What i doing wrong?

Guys? :slight_smile:

When your subscriber template instance is destroyed, it doesn’t clean up the jquery binding you make with $(window).scroll, it will continue to run as if nothing happened. When the scroll then trigger, the template variable in that callback will then refer to the destroyed instance, which causes the error.

You can either clean up/ unbind the scroll binding in the template’s onDestroyed callback, or check that the instance exists before subscribing and clean up if it doesn’t.

1 Like

Jorgeer, thank you very much! :cake:
Gosh! You are absolutelly right.
Im still dont understand why meteor don’t unbind jquery’s events when template is destroying… :unamused:

Meteor actually might do that if you bind the events to elements within the template using
(you’re better off using the built in event system though)
But as you used the global jquery selector, refering to an element that is out of the template’s control, it is out of meteor’s hands so to speak.

1 Like

Now i understand. Thank you once again! :thumbsup: