Document event listener not unbinding in Tracker.autorun() or when Template Destroyed

65 views Asked by At

after dismissing a menu by clicking anywhere else on the page, I noticed when console logging from the callback that document.body will 'remember' the previous event listeners after I move on to another template and trigger the same behavior. The callback is dismissMenu found below. For example...

First time:

hello

Second time:

hello hello

Etc....

What am I doing wrong here?

Thanks!

// named callback to dismiss menu so I can unbind later using $.off()
const dismissMenu = function() {
  console.log('hello')
  $('.js-dd').addClass('js-hidden')
  Session.set('menuOpen', false)
  $(document.body).off('click', dismissMenu)
}

Template.app_bar_expanded.onCreated(function() {
  this.stackId = FlowRouter.getParam('_id')

  // opening the menu will trigger the Session var to 'true'
  Tracker.autorun(function() {
    const menuIsOpen = Session.get('menuOpen')
    if( menuIsOpen ) {
      $(document.body).on('click', dismissMenu)
    }
  })
})

// Stem the event bleeding some...
// TODO get this .off() to actually work as you would expect.
Template.app_bar_expanded.onDestroyed(function(){
  $(document.body).off('click', dismissMenu)
})
0

There are 0 answers