Reputation: 1869
I have created a page which will be loaded via ajax. On this page i have created a function which will assign some function for the specified keys [I'm using jquery Hot keys].
Here is the function that i use to assign functions
function setupKeys()
{
$.each(keyMap, function (event, listener_name){
$(document).bind('keydown', event, listener[listener_name]);
});
}
This will be executed each time when page is loaded.
If l load the page for the first time and press enter key the function will executed. Suppose if i load the page again via ajax with out refersing the browser and press the enter key the function executes two times. And i repeat the same the function will be executes three times.
How can i avoid this? keyMap is an object
keyMap = {
'Ctrl+s':'save_data',
'return':'test_return',
'tab':'test_return'
};
listener = new Array();
Please help.
[sorry for the poor English]
Krish.
Upvotes: 0
Views: 1087
Reputation: 1869
Issue Resolved !
As i was using jquery Hot keys following syntax should be used to unbind the event
$.each(keyMap, function (event, listener_name){
$(document).unbind('keydown', event, listener[listener_name]);
$(document).bind('keydown', event, listener[listener_name]);
});
Upvotes: 0
Reputation: 1869
I couldn't resolve the issue with unbind method. So i have modified the function as marc suggested. And i think its working now.
Thank you marc
Upvotes: 0
Reputation: 69905
Try to unbind the event before you bind it to ensure that events are not tirggered multiple times on the page.
$.each(keyMap, function (event, listener_name){
$(document).unbind('keydown').bind('keydown', event, listener[listener_name]);
});
Upvotes: 0
Reputation: 6223
You have to check whether setupKeys has been executed. Just add a variable
var isSetupKeysCalled = false;
that will be set to false
inside of your function.
Upvotes: 0
Reputation: 120400
Why not unbind the event before binding? No probs nothing is bound, prevents double event registration.
function setupKeys()
{
$.each(keyMap, function (event, listener_name){
$(document).unbind('keydown', listener[listener_name]);
$(document).bind('keydown', event, listener[listener_name]);
});
}
Upvotes: 1