Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you bind an event handler only if it doesn't already exist?

Tags:

I have a page that I'd like to bind drag/drop events to. I'd like the entire page in the browser to be the drop target, so I've bound my events to the document object. My application's content is loaded in the main content area via AJAX, though, and I'd only like these event handlers to be active when the upload page is currently visible.

Right now, I'm binding the event handlers when the upload page is retrieved; however, each time the upload page becomes active, it binds a new event handler, which is causing the handler to fire multiple times when the user goes to the upload page, leaves, and then comes back. I was thinking I could resolve this if I could make the handler bind only when it's not already bound. Is this possible, or am I overlooking a better alternative?

Relevant code, if it helps:

$(document).bind('dragenter', function(e) {     e.stopPropagation();     e.preventDefault(); }).bind('dragover', function(e) {     e.stopPropagation();     e.preventDefault(); }).bind('drop', function(e) {     e.stopPropagation();     e.preventDefault();     self._handleFileSelections(e.originalEvent.dataTransfer.files); }); 
like image 350
FtDRbwLXw6 Avatar asked Jul 23 '12 12:07

FtDRbwLXw6


People also ask

Which method attaches an event handler to an element without overwriting existing event handlers?

The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events.

How do I add event listener only once?

Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.


1 Answers

Unbind existing event handlers before you bind the new ones. This is really straightforward with namespaced events [docs]:

$(document)   .off('.upload') // remove all events in namespace upload   .on({       'dragenter.upload': function(e) {           e.stopPropagation();           e.preventDefault();       },       'dragover.upload': function(e) {           e.stopPropagation();           e.preventDefault();       },       // ...   }); 
like image 59
Felix Kling Avatar answered Oct 12 '22 12:10

Felix Kling