2

I have page which contains jQuery code:

$('#tstButton').live('click',function(){
  alert();
});

And I load this page from ajax call.

When I load the page multiple times, each time it loads the script and stores to cache.

Say when I make ajax call three times. and click $('#tstButton') once, then it will alert 3 time.

I have used:

cache:false

in ajax call. But still its not clearing cache.

How can I clear these javascript codes from cache?

1
  • But your problem has nothing to do with cache but on how you call this snippet, surely from ajax callback. Commented Jun 26, 2015 at 6:02

3 Answers 3

3

You can unbind the event first before binding using die() if you're using jQuery < v1.7.2.

$('#tstButton').die('click').live('click', function() {
    alert();
});

If you're using jQuery v > 1.7.2

You can use on and off:

$('#tstButton').off('click').on('click', function() {
    alert();
});
Sign up to request clarification or add additional context in comments.

Comments

3

You can OFF your previously binded click using jquery OFF function.

$('#tstButton').off("click").on('click',function(){
    alert();
});

1 Comment

die() should be used regarding event bound using live() but that's just bad workaround regarding event bound multiple times
3

In my opinion, it is not a good solution to bind \ unbind event every time when you have dynamically loaded page.

You can use event delegation and bind it only once.

Execute this once on page load and it will properly work on any dynamically added elements:

$(document).on('click', '#tstButton', function() {
    alert();
});

document can be replaced with more precise non-updating container which stores this button.

Here is a working JS Fiddle Demo

1 Comment

bind it only once Ya, that's how it should be done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.