-1

What's the good reason for removing an event handler after using it in javascript or unbinding after binding it in jQuery?

for example, binding and unbinding in jQuery..

$( "#foo" ).bind( "click.myEvents", handler );   
$( "#foo" ).unbind( "click.myEvents", handler );

Or in javascript,

document.getElementById("myDIV").addEventListener("mousemove", myFunction);
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
Yetimwork Beyene
  • 239
  • 1
  • 11
  • I guess, we can avoid triggering event during event propagation. That's quite unnecessary. – Rajaprabhu Aravindasamy Jul 31 '14 at 05:08
  • A good case to remove an event is when you... wait... nvm there is no good case where you should remove an event. I guess unless you're removing the element, but with jquery, that's cleaned up for you. – Kevin B Jul 31 '14 at 05:13
  • I suggest you take a look at this: http://stackoverflow.com/questions/18233199/jquery-bind-unbind-and-on-and-off – Julian Camilleri Jul 31 '14 at 05:13
  • If you can't find a good reason, it means that you don't need to remove the listeners. – Ram Jul 31 '14 at 05:18
  • One good use case is http://api.jquery.com/one/. Otherwise not many reasons to use removeEventListener. – tcooc Aug 01 '14 at 18:51

5 Answers5

2

The uses for this can be many and truly depends on your use case. Sometimes you only want an event to run once and you unbind after running your event listener finishes its function.

In certain apps such as a backbones app it comes down to performance. For example events that are bound to a view let's say, a view for an about page, will be persistant.

Let's say you want to switch between your about view to your "home" view. In backbone the events you define will still exist in memory even if you destroy the object they are bound to within the Dom. In the this case you will have a remove method, or something similar, that will unbind those events for your view object. This is extremely useful for a complex app. But these are only two examples. It's merely a tool and with that you can provide functionality for a large plethora of cases.

codewizard
  • 1,029
  • 1
  • 13
  • 22
1

The main reason to remove an event listener is when you no longer want to be notified of that event, even if it occurs again in the future. This is not the most common behavior and you generally do NOT need to remove event handlers after they fire. For example, removing a button click event handler after it fires would render the button inoperable going forward.

There are examples of a situation where you might want to remove an event handler. A most common one might be that you're registering an event handler for the end of a specific CSS animation sequence. The code that is running now wants to know when the current animation is done, but there may be other animations running later in the program on this element and this code does not want to know about them. So, you install the event handler now when you kick off the animation and then when it fires, you remove the event listener.

FYI, jQuery offers the .one() version of .on() which will automatically remove the event handler after it fires. I use that extremely rarely. Generally I want an event handler (particularly click or key event handlers) installed for the duration of the lifetime of the page.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

In general, if you don't need the event listener any longer, it is safe (or even preferred) that it would be removed/unbound. This may be due to a change in conditions on the page, or simply because you only want the event to be run a finite number of times.

One potential case: a website loading views via asynchronous requests where DOM elements may be loaded/unloaded without a full page refresh.

Other conditions where an event listener is no longer required, you can unregister (or unbind) the event in order to remove the listeners from memory. This can improve webpage performance.

djreed
  • 2,673
  • 4
  • 22
  • 21
  • 1
    This is a bad explanation. They wouldn't have built the function if it didn't have a use. I implore you as a fellow developer to delete or modify you answer so that future developers aren't mislead by misinformation due to googling this post. – codewizard Jul 31 '14 at 06:00
  • @CodeWizard I've edited my original reply. When I read OP's code, I thought this was a complete example of something he had written. It would _never_ make sense to in one line add an event listener, and then in the next line unbind the listener. I thought this was the OP's question. If the answer isn't comprehensive enough, I'm open to suggestions :) – djreed Jul 31 '14 at 06:20
  • Thanks for updating. Your answer makes total sense to me. But I truly understand async. I feel that most people who will need this answer aren't fully aware of how async works. While you answer is sufficient I just want this to be accessible to Jr developer. I don't mean to insult. Your answer is spot on now. – codewizard Jul 31 '14 at 06:24
  • @CodeWizard I do understand what you're saying. If you have another simpler example let me know. – djreed Jul 31 '14 at 06:29
  • Totally. I would assume anyone who knows this answer knows async and what the Dom truly is, while those who don't wouldnt. I suggest utilizing the keywords "single page app" and the concept of changing a "page" within. I feel even my answer is too verbose. Thanks for the consideration. – codewizard Jul 31 '14 at 06:37
0

In a dynamic app you might load several screens without needing to refresh the page. When you initialize a new screen you might want to start listening for events. Now if you load a different screen (into the same tags) you'll end up with multiple listeners for the same event. This might cause a series of events to fire when you only want one.

So some offensive code might look like this:

var loadScreen1 = function(){
    $(".content").html("<p>Screen 1</p>");
//  uncomment the following to "fix"
//  $("#toggler").unbind('click');
    $("#toggler").click(toggleScreen);

    $(".history").append(" -1- ");
}

var loadScreen2 = function(){
    $(".content").html("<p>Screen 2</p>");
//  uncomment the following to "fix"
//  $("#toggler").unbind('click');
    $("#toggler").click(toggleScreen);
    $(".history").append(" -2- ");
}

var currentScreen = 1;

var toggleScreen = function(){
    if (currentScreen == 1){
        loadScreen2();
        currentScreen = 2;
    } else {
        loadScreen1();
        currentScreen = 1;
    }
}

loadScreen1();

Here is a fiddle where something like this can go terribly wrong:

http://jsfiddle.net/9D4J5/1/

Andy Novocin
  • 454
  • 3
  • 14
  • While this answer is contrived, when using Backbone you have event listening that is not tied to the DOM at all. In that case events which are not killed can cause the targets to not be garbage collected despite being removed from view. This creates disembodied zombie issues when you aren't careful to stop listening. – Andy Novocin Jul 31 '14 at 05:48
-2

You can use bind() to associate new behavior with an element, which can be removed later with unbind(); in other words you can create a temporary behavior for a element.

e.g.

  • make an element clickable based on a condition
  • add a different mouseover tooltip to an element based on user actions
  • make a submit button defunct after a timeout
  • be notified of events now, but that you don't care about later (= temporary behavior right?)
  • modify keyboard event handlers based on context
  • cancel an action that will fire a bunch of events that will no longer be applicable
  • ...
dnozay
  • 23,846
  • 6
  • 82
  • 104
  • 2
    if you downvote, please clarify why. – dnozay Jul 31 '14 at 05:17
  • 1
    I don't think this question is asking what unbind and bind does. – Kevin B Jul 31 '14 at 05:22
  • you can use `unbind` in different situations; if a behavior is permanent, then there isn't a good reason for `unbind` unless you have some implementation details that force you to use it... e.g. duplicate calls to the same handler. – dnozay Jul 31 '14 at 05:25