Rebinding in jQuery

There is one problem in jQuery that really took a while to figure out(and I’m probably not the first one this happens to), but when I got it – I’ll hopefully never forget it. It’s about ajax part of it, when you have for instance a button with and click event attached to it, and want the same event to be attached to the button returned by ajax. I thought, yea, it should be automatic, but guess what? It was not. The event did not work on the new button added to the page dynamically and I did not get why.

My code was like this:
$(".button").click(function(){
//Do stuff
})

The same as this:
$(".button").bind("click", function(){
//Do stuff
})

The solution was kind of simple, you have to rebind the event to the button that returns from backend. The hard way to do it is to copy the code, or make a method with the code, that is run once the page loads and when the new button arrives to bind it again. But that is just wrong, so I’m glad jQuery had a better answer.

The answer is the .live() method that works exactly the way .bind() does but also in the future:
$(".button").live("click", function(){
//Do stuff
})

I think it’s also possible to use the method .delegate(), where you can delegate the listener to a selector in a specific context like this:
$("body").delegate(".button", "click", function(){
//Do stuff
})

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: