Solution to avoid binding Events Multiple times to a particular control using jquery


Background: 
I created a Popup which is populated when I click a link.Popup has a button to which I have bound a click event that open a new window. I am doing everything using jquery.

Scenario:

  1. I open Popup 1st time,When I click button a new window gets opened.
  2. I close and reopen popup(this is 2nd time), now I click button. At this time two window gets opened.
  3. I close and reopen popup(this is 3rd time), now I click button. At this time three window gets opened.


What went wrong:
My code to open popup was correct but what I did wrongly was a minor but a serious mistake.
I wrote a code of binding event to button, inside the function and I was calling it each time I open a popup!
So, basically each time my function was getting called it was binding event to button. That means, button was getting bound multiple times with the same event!

Solution I applied:
To handle this case, I moved my event bind function call to the document.ready function.
That means, each time my button will get rendered, I will bind event as on each rendering  button will not retain previous binding.

0 comments:

Post a Comment