I have a common function for many pages as below
function (){
resetForm();
$ajax call
{
// some code //
}
}
now if i have not written the resetForm() fn in correspoding js, its giving the uncaught reference error as it should give and also my code followed after than line is not executed.
The js files where i have written resetForm fn() is working fine, but others are not.
The solution i have now is writing a blank resetForm function in other pages. Any other way ?
thanks for the help
You can check with typeof
if (typeof resetForm === 'function') {
resetForm()
}
// carry on.
This checks to see if you have a function called resetForm available and, if you do, executes it.
you can check it it exists (globally) and only than call it by:
window.resetForm && resetForm();
Here's a few obvious options:
Write a blank function like you did.
typeof resetForm === 'function' && resetForm();
Make sure to load only code that is relevant to the current page by better modularizing your code.
just check if resetForm is defined:
if (resetForm) {
resetForm();
}
I know it's not jquery-tagged question, but consider using jquery's onReady handler, it is executed when all javascript is loaded.
//main.js
$(function(){
resetForm();
});
//functions.js
function resetForm() { .. }
It will call resetForm properly event if resetForm is in separate js and loaded after main.js is loaded.
Related
I am writing a code that performs a function on click on a set of elements. It has a revalidate function. This revalidate function is fired on window resize. It checks if certain conditions are not fulfilled after resize then nothing should be done on click on body. This is an oversimplified version. Code:
var myFunction = function() {
// do something
}
var myCallback = myFunction;
$(".myClass").on("click", myCallback);
$(window).resize(function(){
if(//certain conditions are met) {
myCallback = undefined;
}
else {
myCallback = myFunction
}
});
I know I can use jquery off to detach the handler. But the actual code is more complex. It is a plugin like code where if I click event is bound in certain conditions inside the plugin definition. If I use off then to use On again appropriately I might have to run the whole plugin code once again; that beats the purpose of revalidate function. So,
Is it ok to execute undefined callback in event listeners?
P.S: I have been also reading about jQuery.noop. Seems like it's the exact situation to use that.
Your code doesn't call an undefined function, because the variable myCallback is only evaluated when you bind the event handler, not every time the event occurs. To have the question you ask, it would have to be the following code:
$(".myClass").on("click", function(e) {
myCallback.call(this, e);
});
When myCallback is set to undefined this will get an error, complaining that undefined is has no property call. What you should write is:
$(".myClass").on("click", function(e) {
if (myCallback) {
myCallback.call(this, e);
}
});
When you do this,
$(".myClass").on("click", myCallback);
A reference to myCallback function is sent. When reassigning it, the callback (reference) sent to the on function will not be changed.
What you probably wanted to do is something like this
$(".myClass").on("click", function(){ myCallback(); });
Now when myCallback is undefined, you'll get an error saying it's not a function. You could assign it an empty function instead of undefined:
myCallback = function(){};
Alternately, you could check for the condition within the click handler:
var condition = true;
var myFunction = function() {
if( !condition )
return;
// do something
}
$(".myClass").on("click", myFunction);
$(window).resize(function(){
if(//certain conditions are met) {
condition = false;
}
else {
condition = true;
}
});
The way which you tried didn't work as you didn't pass your callback physically, just a pointer to it. So doing
myCallback = undefined;
Doesn't clear your callback, it just changes pointer to undefined variable. jQuery saves information about your callback before you change the pointer. That's why it didn't work.
Consider refactoring to:
let guardian = true;
let clickHandler = function () {
if (guardian) {
/* your code */
}
};
$(".class").on("click", clickHandler);
$(window).resize( function () {
if (/* certain conditions are met */) {
guardian = false;
} else {
guardian = true;
}
});
In that case, we change guardian variable during resizing and check against it in our click handler. You don't have to on/off your callback handlers in such a case.
It's certainly not pretty code, and steps should be taken to make it obvious to other developers (or future-you) that this callback may not be a callback later on, but jQuery's .on method will not try and run anything that equates (think ==) to false.
Therefore, setting your callback to undefined will not error.
I have a function that already defined. I need to to call the function with parameters when the jQuery swipe event occurs.
Here is the code
$( document ).ready(function() {
$("#next").on("swiperight",myFunction('right'));
$("#next").on("swipeleft",myFunction('left'));
function myFunction(direction) {
var dir = direction;
console.log(dir);
}
});
But id doesn't works onswipe. Instead it works twice on page load and prints right and left in console.
It works when the function is called without arguments like,
$("#next").on("swipeleft",myFunction);
What is the problem here ? Appreciate for any help.
Callback functions have no name. Wrap your named functions inside it:
$("#next").on("swiperight",function(){myFunction('right')});
$("#next").on("swipeleft",function(){myFunction('left')});
I have a script with the following structure:
Test = {
CONSTANTS : {},
VARIABLES : {},
MARKUP : {},
FUNCTIONS : {
init : function () {
// Access variable from different namespace
var all_constants = DifferentNamespace.CONSTANTS; // WORKS
var tester = DifferentNamespace.CONSTANTS.chunk_of_markup; // SAYS UNDEFINED
}
},
init : function () {
// Call real init() function
$(document).ready(function () {
Test.FUNCTIONS.init();
});
}
};
$(document).ready(function () {
Test.init();
});
If I remove either of the $(document).ready(..) function calls, when I try to access a constant from a different namespace it is undefined; with both is works well.
As you can see I'm using two init() functions, one it just to neaten up the call to init because I have wrapped functions inside an additional object.
If I remove the function that is on the same level as CONSTANTS, VARIABLES etc and try to call the init() within Test.FUNCTIONS it still does not work.
Edit:
If i console.log(all_constants) I get the full object (with .chunk_of_markup) but if I console.log(tester) is get undefined. If i wrap tester i get []
I should also note that the other namespace gets the markup from a seperate file.
Any ideas why?
Having two document ready doesn't make a difference here. You could have one document.ready and/or call Test.FUNCTIONS.init directly and all should work, and the fact that they are in different namespaces doesn't matter as well.
As for why you're getting undefined, I think it is probably because your chunk_of_markup variable is actually undefined at that point. My guess is that you're getting the value for it through AJAX and so the call is done asynchronously which means the DOM will be ready before it actually returns a value. When you use the Debugger then the value is evaluated at the point of time where you run the command so by then, the async call already returns successfully (it's a race condition, if you're fast enough and your AJAX is slow then you can still get undefined, and it's also why 2 ready functions happen to make it slow enough for the AJAX call to return but it's still unreliable).
In all cases, if my theory is correct, then you need to hook to the callback of the AJAX request rather that DOM ready event, this is the only place where you can guarantee that your variable is defined.
Why not call the function init() in the document Handler itself.. I don't think that will lead to the same problems.. You can remove the Test.init() completely as it does not seem to do anything in here
Test = {
CONSTANTS : {},
VARIABLES : {},
MARKUP : {},
FUNCTIONS : {
init : function () {
// Access variable from different namespace
var all_constants = DifferentNamespace.CONSTANTS; // WORKS
var tester = DifferentNamespace.CONSTANTS.chunk_of_markup; // SAYS UNDEFINED
}
}
};
$(document).ready(function () {
Test.FUNCTIONS.init();
});
So Safari keeps yelling at me for one specific error.
I'm trying to use Google Maps API and call map.getCenter();. However sometimes, this happens before the map has been fully loaded.
So instead in my function I test for an undefined call like this:
if (map.getCenter() != undefined)
But that still errors out because I guess it doesn't even like making the call just to test the if the result is undefined or not?
Can I get some help here?
Thanks!
I actually prefer something along these lines.
if(typeof myfunc == 'function') {
myfunc();
}
Just because something isn't undefined doesn't make it a function.
if (typeof map !== 'undefined' && map.getCenter) {
// code for both map and map.getCenter exists
} else {
// if they dont exist
}
This is the right way to check for existence of a function.. Calling the function to test its existence will result in an error.
UPDATE: Snippet updated.
if (typeof map.getCenter !== 'undefined')
Won't throw an error.
So, better yet, if (typeof map.getCenter === 'function') map.getCenter();
Technically you should be testing if map is undefined, not map.getCenter(). You can't call a function on an undefined reference.
However, Google's own tutorial suggests that you invoke your JavaScript that accesses the API in a body.onload handler, so that you do not attempt to reference anything until all of the remote .js files are loaded - are you doing this? This would solve the problem permanently, rather than failing cleanly when your JavaScript executes prior to loading the API.
I have been in the habit recently of using the typeof operator to test for things and types. It returns the type as a string which I think avoids some response type confusion.
if( typeof map.getCenter != 'undefined') ...
I'm not sure if it's more correct, but I find good results with this process.
You should be testing whether map is undefined. In your current check your are still trying to execute the function call.
Assuming that map.getCenter() is always a function, it's sufficient to just use this check:
if (map.getCenter) {
var x = map.getCenter();
}
The worked solution for me is try and catch,
const stopPropagation = (e) => {
try {
e.stopPropagation();
} catch (err) {
console.log("error with stopPropagation: " + err.error);
}
}
const triggerClick = (e) => {
stopPropagation(e);
};
Can anyone can give me a JavaScript code snippet by which I can detect if a JavaScript function is loaded in my aspx web page or exists before calling it?
Thanks
This will check if your function is defined.
if (typeof functionName === 'function') {
alert('loaded');
}
See it.
You could explicitly check that it's a function before calling it.
if (typeof(functionName) == "function")
functionName();
What do you mean by loaded?
In general you should use something like the onload event to make sure all your scripts have been loaded before you call them. In case you just want to whether a function has been declared or not you can use the typeof operator:
// Check the type of "myRandomFunction"
// Note: typeof is the only way you can use undeclared variables without raising an exception
if (typeof myRandomFunction === 'function') {
myRandomFunction()
}