简体   繁体   中英

Unbinding key events in Meteor?

I have a template which has a key event

Template.layout.events({
  'keyup': function (e, template) {
    if (e.keyCode === 13) {
      e.preventDefault();
      // do some stuff here, isn't important for question
      Router.go('Users.profile', { _id: id });
    }
  }
});

However, when I change pages, it seems the event is still bound to the enter button.

I imagine the first step is to use an onDestroyed callback on my template.

Template.layout.onDestroyed(function () {
  // ???
});

How would you unbind key events on page change in meteor?

It doesn't look like Meteor natively supports removing events added via Template.name.events . There are a few resolutions I can think of in this case:

  1. Handle the special case inside the Event handler, which means coupling the handler with the rest of the application logic. This may or may not suit your needs.
  2. Attaching a (namespaced) event handler .onRendered using jQuery and then removing it explicitly .onDestroyed .
  3. Bind the keyup event more tightly to the element in focus. If that element is removed from the DOM, the handler will also be removed.

Event handlers are destroyed automatically when the template is destroyed. But, with a name like layout , I'm guessing that template exists on multiple routes. If this is the case, add a console.log to onDestroyed() and see if it even gets destroyed when you want it to. To fix this, attach the keyup listener on a more specific template, for instance if you have this

<template name="layout">
  {{>settingsMenu}}
</template>

and assuming you only want 'enter' do do something on the settings menu, use: Template.settingsMenu.events Then, when settingsMenu is destroyed, so is the event handler. If you bizarrely don't have one (ie the current route doesn't have a single unique template on it), create one:

<template name="settingsMenu">
</template>

{{>settingsMenu}}

Template.settingsMenu.events({...

Additionally, an ugly fix would be to add a conditional at the top of your event: if (Router.current().route.getName() === 'settingsMenu')... I call this ugly because you still have a rogue event listener there, it's just harmless for all but your specified route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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