Skip to main content

Bug Tracker

Side navigation

#2956 closed enhancement (wontfix)

Opened May 29, 2008 05:09PM UTC

Closed May 29, 2008 11:36PM UTC

Add optional argument for events to unbind before bind

Reported by: ygirouard Owned by:
Priority: minor Milestone: 1.3
Component: event Version: 1.2.5
Keywords: bind event unbind Cc:
Blocked by: Blocking:
Description

If you currently try to bind 2 different functions in a row to the same element, it won't bind as expected. You must unbind before you bind the second one.

i.e.:

We have an image with ID of myImage:

<img id="myImage" src="image.gif">

On page load, I bind .click() as follow:

$(document).ready(function(){
  $("#myImage").click(function(){alert("Foo!")});
});

Later in my page, I want to change the bind to alert "Bar!" instead. If I just try to "rebind" click, it will still do alert("Foo!"); and will ignore the new function.

To get it to work, you have to unbind before you rebind as follows:

$("#myImage").unbind("click").click(function(){alert("Bar!")});

What I suggest is to add an optional boolean argument to all events such as "click" to unbind before bind (default would be 'false' to keep backwards compatibility).

So the syntax of .click for example, could be:

.click(fn,[unbind])

Example:

$("#myImage").click(function(){alert("Bar!");},true);
Attachments (0)
Change History (1)

Changed May 29, 2008 11:36PM UTC by flesler comment:1

resolution: → wontfix
status: newclosed

This really isn't such a useful change. The unbind().bind() is widely used and it's not really too problematic.

Also, you could consider doing this "logic" inside the handler:

var areWeThereYet = false;
$("#myImage").click(function(){
   if( !areWeThereYet  )  
     alert("Boo!");
   else
     alert("Yay!");
});