Paying attention to your event binding in jQuery 0
When doing event binding in jQuery on a page that has a lot going on, it might be best to make sure you unbind and rebind the events, just to make sure you only get one event per element. I recently ran into an issue where the number of events triggered grew exponentially, and it was linked to this. Luckily, jQuery has a nice convention for working with rebinding. For instance, if we were binding to a button’s click event, and wanted to make sure this method was only ever called once when this button was clicked, we could do the following:
1 2 3 4 5 6 7 8 | ... $("#some-button-id").unbind("click", buttonClickCallback) .bind("click", buttonClickCallback); ... function buttonClickCallback(e) { // code for the button click event } |
This way, we explicitly remove and reset the function that will be called when that button is clicked. Inside the function body, you can still use $(this), just as you would do had you written the function inline. There are a couple of variations to the unbind method: without any arguments, it can unbind ALL bound events, and with only the event type, it will unbind all events of that type.
You can read more about bind and unbind with jQuery in the official jQuery documentation at http://docs.jquery.com.
