$(window).scroll(...) Is Running Even If The Template Is Destroyed In Meteor
I have two separate template and in both template(rendered) i am doing $(window).scroll() but however go to one template another, the $(window).scroll() is running from both, previ
Solution 1:
Destroying a template in Meteor will perform internal cleanup regarding the template rendering engine (Blaze
) and it will unregister events declared via template event maps, but it won't unregister global window events Meteor is not aware of.
After registering a custom global event in the onRendered
lifecycle event callback using $.on
, you'll need to unregister it in the onDestroyed
callback using $.off
.
You can use this pattern to register and unregister handlers :
Template.dashboard1.onRendered(function(){
this.scrollHandler = function(){
// you can use the this keyword here to reference the template instanceconsole.log("dashboard1 scroll");
//... doing pagination and sticky element for dashboard1
}.bind(this);
$(window).on("scroll" ,this.scrollHandler);
});
Template.dashboard1.onDestroyed(function(){
$(window).off("scroll", this.scrollHandler);
console.log("dashboard1 destroyed");
});
By attaching a this-bound function as a property of the template instance, you can perform template instance specific logic inside the event handler.
Solution 2:
you need to remove your listener manually when template is destroyed.
var scrollHandler = function() {
console.log('dashboard1 scroll');
}
Template.dashboard1.rendered = function() {
$(window).scroll(scrollHandler);
}
Template.dashboard1.destroyed = function() {
$(window).off("scroll", scrollHandler);
console.log('dashboard1 destroyed');
}
Post a Comment for "$(window).scroll(...) Is Running Even If The Template Is Destroyed In Meteor"