Ajax refresh javascript duplicates event

Ajax refresh javascript duplicates event

  

Hi!

So I have a div and inside div there is an expression with piece of javascript:

"<script>
$.key('esc', function() {
    alert('esc');
}); 
</script>"

Then there is a button that has the method ajax submit and in the action it does a ajax refresh of the div.

Then after pressing the button a few time and then pressing esc I will get the alert multiple times.

It looks like its duplicating the piece of code in the expression because of the ajax refresh.

Any idea how to fix this?


Hi Nick,

I vaguely recall having the same problem a while ago, but I can't for the life of me recall what I did to solve it, sorry :). That said, it might've something to do with the specific container I refreshed. Have you tried Ajax-refreshing the whole screen, just to see if it still happens?

There is no way to do a ajax refresh on the whole page right? With the ajax refresh you need to select a widget.

True, but usually you'd have some top-level Container you can refresh.

That's what I'm doing refreshing the top container of the page. For a demo, I removed everything from the page and added only one container 1 expression in the container and a button to do the ajax refresh.

Just to make sure, have you used your browser's devtools to check whether the code is actually duplicated on the page? Multiple triggering a piece of code could have more causes.

when I use firebug and get the HTML of the page I don't see the script multiple times.

Ok, in that case something else must be the case. It may have to do with pressing the button multiple times, but I'm not good enough with JavaScript/JQuery and the way it handles keypresses to know what could be causing this.

Hi Nick, 

Why not changing the script, something like:

if($('.Page').hasClass('alert-added')){

    /*not sure if you want to do some code here*/

}else {

$.key('esc', function() {
    alert('esc');
});

$('.Page').addClass('alert-added');

}

Let me  know if it worked

Hi Nick,

If you want your piece of javascript code to run only once independently of the number of refreshes, you can also add that piece of code (without the <script> tags) in the Javascript property of the WebScreen or WebBlock.

Cheers,

José 

Hey Nick,

You can use this script, Working same as you want but not run multiple times

"
<script>
$(document).keyup(function(e) {
     if (e.keyCode == 27) { 
        // escape key maps to keycode `27`
        alert('esc');
    }
});
</script>
"

Exactly same problem!


Gopal Jite wrote:

Hey Nick,

You can use this script, Working same as you want but not run multiple times

"
<script>
$(document).keyup(function(e) {
     if (e.keyCode == 27) { 
        // escape key maps to keycode `27`
        alert('esc');
    }
});
</script>
"