Event Listener Duplication on Page Navigation SammyJS

84 Views Asked by At

I am using SammyJS framework for my routing.

As my title reads, I am having a problem with event listeners on my web page. In my code I have 4 main pages, clients/sensors/dashboard/status. On the sensors page it loads many different sensors. As well as being able to edit the sensor metadata, there is a button to add an owner to the sensor. The HTML for the page and button is loaded only when going to the edit page. It looks like this Here is a shaved down version of the Javascript...

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

  app.get('#/sensors', function(context) {
    //context.render the index page...
  });

  app.get('#/sensors/edit/:sensor', function(context) {
    context.render('/views/sensors/edit.html', function(view) {
      $('#result').html(view);

      $(document).on('click', '#addCustomer', function() {
        //Add another dropdown customer list...
      });
      
      //More event listeners...
    })
  })
})();

What happens is that if I navigate away from that page, then back to it (doesn't have to be the same sensor edit page) and then click ADD CUSTOMER, it adds two. Each time I navigate away then back to, it adds 1 to the amount of dropdowns it adds. My first thought was that the event listeners are somehow being duplicated but I have no idea how to test for that. Any help is greatly appreciated.

1

There are 1 best solutions below

0
Jam On

Take a look at the jQuery "one" method which will ensure the event handler is only bound once: http://api.jquery.com/one/

$("#addCustomer").one("click", function(event) {
   //Add another dropdown customer list...
});