简体   繁体   English

文档级事件监听器被复制

[英]Document level event listeners being duplicated

I am using SammyJS to route a website, and I'm also using this file structure, 我正在使用SammyJS来路由网站,并且也在使用此文件结构, Inside of my controller/ , I have 4 main pages. 在我的controller/内部,我有4个主页。 Inside, they look like this, 里面看起来像这样

 (function() { var app = Sammy.apps.body; app.get('#/clients', function(context) { context.render('/view/clients/index.html', function(view) { $('body').html(view); }); }); app.get('#/clients/edit', function(context) { context.render('/view/clients/edit.html', function(view) { $('body').html(view); $(document).on('click', '#updateClient', function() { //Do stuff for updating client here... }); }); }); }); 

With the first navigation everything works fine. 通过第一次导航,一切正常。 The HTML and JavaScript load perfectly and the buttons work as intended. HTML和JavaScript可以完美加载,并且按钮可以按预期工作。 But upon page navigation (I'm using href 's to handle the navigation) to another page and then back, the event listeners are being duplicated, as can be seen here (using Chrome) 但是在页面导航(我正在使用href来处理导航)到另一个页面然后返回时,事件监听器已被复制,如此处所示(使用Chrome)

Before(first navigation) 之前(第一次导航)

After(second navigation) 之后(第二个导航)

Is there any way to stop this? 有什么办法可以阻止这种情况? I understand using $('#idNameHere').on('click', function() {...}); 我了解使用$('#idNameHere').on('click', function() {...}); works, but not on dynamically generated elements. 有效,但不适用于动态生成的元素。 Also, page refresh works to delete the listeners (sort of obvious). 同样,页面刷新可以删除侦听器(很明显)。 I am led to believe that could also be part of SammyJS's way of running, where it keeps JavaScript files running in the background even after you navigate away from the page. 我相信这也可能是SammyJS的运行方式的一部分,即使您离开页面,它也可以使JavaScript文件在后台运行。

You can just move the event listener out to the root, so that it's set only once. 您可以将事件侦听器移到根目录,以便仅设置一次。 Since the event listener is set on the document, it'll work fine with dynamically added content. 由于事件监听器是在文档上设置的,因此可以与动态添加的内容配合使用。

(function() {
  var app = Sammy.apps.body;

  $(document).on('click', '#updateClient', function() {
    //Do stuff for updating client here...
  });

  app.get('#/clients', function(context) {
    context.render('/view/clients/index.html', function(view) {
      $('body').html(view);
    });
  });

  app.get('#/clients/edit', function(context) {
    context.render('/view/clients/edit.html', function(view) {
      $('body').html(view);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM