Search code examples
meteormeteor-blazeflow-router

Can’t call View#subscribe from inside the destroyed callback


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.

PIRNT SCREEN CONSOLE

What i doing wrong?


Solution

  • Owch! The good guy from meteor forums helped me. Actually the problem is in jquery.scroll event. It not cleaned up when template is destroyed. (Is it a bug? Or it is normal behavior?). I just needed to unbind the scroll event in onDestroyed section.