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


#1

Hello!

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.

Code:

  Template.subscriber.onCreated(function() {
        var template = this;
        var skipCount = 0;
        template.autorun(function(c) {
            template.subscribe(template.data.name, skipCount, template.data.user);
            var block = true;
            $(window).scroll(function() {
                if (($(window).scrollTop() + $(window).height()) >= ($(document).height()) && block) {
                    block = false;
                    skipCount = skipCount + template.data.count;
                    console.log(template.data);
                    console.log("skip_count is "+skipCount);
                    template.subscribe(template.data.name, skipCount, template.data.user, {
                        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?


#5

Guys? :slight_smile:


#6

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.


#7

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:


#8

Meteor actually might do that if you bind the events to elements within the template using
template.$(".my-element-in-template").click(....
(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.


#9

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