javascript : Event execute multiple time after loading page via ajax. - javascript

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.

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]);
});
}

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.

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]);
});

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

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]);
});

Related

how could the callback function of addEventListener() works even if we didn't pass the event object into the function

const eventHandler = function (eventObject) {
console.log('You clicked on the page')
console.log(eventObject)
}
document.addEventListener('click', eventHandler)
So the codes above, as you can see we are listening to the click event on the page, with a "seperated" callback function, or an event handler function named eventHandler. And you can see this eventHandler function it expects an eventObject parameter which is the event object itself.
You can see, when i pass the function eventHandler into the addEventListener() method, i didn't passing any argument, right? So i didn't pass the eventObject into it. But, when i run the codes, the codes still running without error, so when i clicked on the page, i get a You clicked on the page message, and the event object.
Why is that? How could that function can log the event object into the console, when it requires us to pass the event object into it as an argument and we didn't do that? And that is my question. I got into this situation when playing around with DOM event, and it really make me confused. So hopefully someone can help me understand, what's going on here! Thank you very much!
Sorry you may want to run this codes on yourself, I will update the demo later, thank you so much!
The reason you don't need to pass an event as a parameter to the function eventHandler that you are calling in the document onclick event listener, is because it already has an event that has been registered to it in the function
const eventHandler = function (eventObject) {
console.log('You clicked on the page')
console.log(eventObject)
}
// document.addEventListener('click', eventHandler)
// This function above is the exact same as the one here below
// That's why it works, because the event object has already been passed to the function
document.addEventListener('click', function(eventObject){
console.log('You clicked on the page')
console.log(eventObject)
})
<h2>Click anywhere to run the function</h2>

Stop JavaScript function when element is pressed

I want a function that will stop another function from running. It can be in JavaScript or jQuery.
It is for a game so div 1 is clicked over and over.
var makeBox=//a function;
$("#div1").click(function () {
makeBox
});
$("#div2").click(function () {
//stop make box
});
I hope it's more clear now
Why don't you try reassigning the event handler function?
var makeBox=//a function;
$("#div1").click(function () {
makeBox
});
$("#div2").click(function () {
$("#div1").click(function(){
//Do nothing
});
});
You might need to reassign it again later if you want it to work again but I don''t know exactly what you are trying to do.
No. JavaScript is single threaded. The click event won't be processed while another function is running.
(Your function might call other functions, using events, timeouts, etc which would allow for interruption, but there isn't any indication of that in your question).

JavaScript calling a function without parenthesis

A few weeks ago I was painfully able to dynamically add buttons to an HTML DOM object that has its own .on('click'.. handler, and use e.stopPropgation to stop these new child elements from firing the event.
The weird thing I did was call a function without any parenthesis. I have no idea why I did this or why it works, or why it does not work when I do attach parenthesis. I want to know if I am doing something by fluke and not design (and now I will add comments to it).
It goes as such:
//Container is the parent element
// var buttons stores the buttons with class 'buttons'
$('.container').on('click', function(){
$(buttons).appendTo($(this)).fadeIn(500).find('.buttons').click(tableButton);
});
function tableButton(e){
e.stopPropagation();
//do stuff
}
I can't figure out why I wrote the call to tableButton with no arguements or why it works perfectly. I tried to change the syntax to
.find('.buttons').on('click', function(e){
tableButton(e);
});
but then it no longer works.
Any help appreciated!
It works because you're passing a function to the click handler rather than calling the function yourself (the ()) An example of that:
var testFunction = function(msg) {
alert(msg);
}
var functionCaller = function(functionToCall) {
functionToCall('hello!');
}
functionCaller(testFunction);
functionCaller passes the message argument to testFunction(), but we only pass testFunction to functionCaller (without arguments)
For the part which doesn't work, isn't the function name tableButton() instead of tableButtons()?
See http://jsfiddle.net/g2PAn/
You don't actually call it, you just declare it and the arguments it accepts. The click callback is called with an argument indeed, but not by you.
The problem probably comes from the fact that jQuery calls your function with the element clicked bound as this, you could call table button like this:
.find('.buttons').on('click', function(e){
tableButton.call(this, e);
});

How to remove a callback function from jQuery widget

I have a widget that I am assigning a callback function to for a specific event.
The following code works and triggers my callback just fine.
$(selector).MyFancyWidget('option', 'onComplete', this._onComplete);
My issue is after the event fires I want to remove the callback from inside the _onComplete method.
onComplete is an event that gets fired in the widget using the _trigger method and works fine.
Doing something like
$(selector).MyFancyWidget('option', 'onComplete', $.noop);
Does not detach the callback ( i assume it is just adding another listener.
For clarity here is the code inside the widget that will trigger the event.
instance._trigger('onComplete', e, {currentTarget: instance});
So my question here is how do I remove that callback?
It's not that I don't want to fire the event anymore I just don't want to listen to it anymore.
The most straightforward way of doing this would be to make the callback only do something once. So wherever you define your _oncomplete function:
var completeRan = false;
this._onComplete = function(e, args) {
if (completeRan) {
return;
}
// Rest of your code.
completeRan = true;
return this;
}

Call an object as a function in JavaScript

I'm trying to execute JavaScript functions that are called when a event (for example onClick event) is performed on a web page with JavaScript code. I'm getting the function from the event like this :
var attributval = document.getElementsByTagName("a").getAttribute('onClick');
and I'm trying to execute this object (which a JavaScript function in fact) as a function (suppose we have <a onClick = alert('whatever');> on this example, I tried:
var attributval = document.getElementsByTagName("a").getAttribute('onClick');
attributval() = function(){attributval};
attributval();
but it didn't work.
A DOM attribute is not the same as a JavaScript property (even though they can have the same name onclick). You should use
var attributval = document.getElementsByTagName("a")[0].onclick;
to retrieve a function (or null) from the JS object (as opposed to getAttribute(), which will most likely return a toString() for the property).
Now, attributval() = is illegal syntax, as attributval() is not an l-value (you cannot assign to it).
attributval(); will work but without the second line (which is illegal JavaScript) it will invoke the original A element onclick handler (if one is defined) or throw an exception (if the onclick handler is null).
Skip trying to create a function around the function. Just call it:
var attributval = document.getElementsByTagName("a")[0].onclick;
attributval();
try
var attributval = document.getElementsByTagName("a")[0].getAttribute('onClick');
By using get attribute you are returning a string so your only way is to use eval(onclickString) or var fn = new Function(onClickString); fn();
attributval is simply a string, correct? If you trust this code, execute it with eval(attributval) -- however any reference to this won't work.
What you probably want is to manually trigger an event. jQuery makes that easy.
If you want to do more than a click, then Chris McDonald's answer at Is it possible to trigger a link's (or any element's) click event through JavaScript? seems to fit the bill, although you might need to heed the third comment.
I thought I'd add a short answer on how to work with events using jQuery, since it seems relevant.
// Select the link using it's ID field (assuming it has one)
var myLink = $('a#myLink')
// Add a click event to the link
myLink.on('click', function(e) {
console.log("I've been clicked!");
});
// Trigger the click event manually. This would result in the above
// function being run. Interestingly, this will not cause the browser
// to follow the link like a real click would
myLink.trigger('click');
// Remove the click event (this removes ALL click events)
myLink.off('click');
// Add a click event to the link that only runs once, then removes itself
myLink.one('click', function() {
alert("I'll only bother you once!");
});
// Add a click event that you can identify from other click events.
// This means that you can trigger it or remove it without bothering other
// click events
myLink.on('click.myClick', function() {
alert("This click event has been identified as 'myClick'");
});
// Now you can trigger it without triggering other click events
myLink.trigger('click.myClick');
// And remove it, also with no harm coming to other click events
myLink.off('click.myClick');
Hope this helps

Categories

Resources