$(window).scroll(...)正在运行,即使模板在流星中被破坏 [英] $(window).scroll(...) is running even if the template is destroyed in meteor

查看:94
本文介绍了$(window).scroll(...)正在运行,即使模板在流星中被破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个单独的模板,并且在两个模板(已渲染)中,我都在执行 $(window).scroll(),但是转到另一个模板,即 $(window). scroll()既从先前的模板运行,也从当前的模板运行.

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, previous as well as current template.

代码片段如下:

dashboard1.js

dashboard1.js

Template.dashboard1.rendered = function(){
    $(window).scroll(function() {
        console.log('dashboard1 scroll');
        //... doing pagination and sticky element for dashboard1
    });
}

Template.dashboard1.destroyed = function(){
    console.log('dashboard1 destroyed');
}

dashboard2.js

dashboard2.js

Template.dashboard2.rendered = function(){
    $(window).scroll(function() {
        console.log('dashboard2 scroll');
        //... doing pagination and sticky element for dashboard2
    });
}

Template.dashboard2.destroyed = function(){
    console.log('dashboard2 destroyed');
}

控制台:

dashboard1 destroyed
dashboard2 scroll
dashboard1 scroll
dashboard2 scroll
dashboard1 scroll
dashboard2 scroll

但是如果我刷新浏览器,则说明它仅来自当前模板.

But if i refresh the browser, then it is coming from current template only.

为什么会发生这种想法?解决此问题的方法是什么?

Why this is happening any idea? what is the way to fix this.

推荐答案

在Meteor中销毁模板将对模板渲染引擎(Blaze)执行内部清理,并且将取消注册通过模板事件映射声明的事件,但它成功了不要取消注册流星不知道的全局窗口事件.

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.

使用$.ononRendered生命周期事件回调中注册自定义全局事件后,您需要使用$.offonDestroyed回调中注销该全局事件.

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 instance
    console.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.

这篇关于$(window).scroll(...)正在运行,即使模板在流星中被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆