How to check if is function on jquery, but function is in another .js file?
validation.js:
if ($.isFunction('payment')) {
$('[data-numeric]').payment('restrictNumeric');
$('.cc-number').payment('formatCardNumber');
$('.cc-exp').payment('formatCardExpiry');
$('.cc-cvc').payment('formatCardCVC');
}
this is false because func payments is in the payments.js .
Try like this
if (typeof payment === "function")
{
// Do something
}
problem is solved. its works:
if ($.fn.payment) {
//do something
}
Try to check like as follows,
if (typeof payment !== 'undefined' && $.isFunction(payment)) {
$('[data-numeric]').payment('restrictNumeric');
$('.cc-number').payment('formatCardNumber');
$('.cc-exp').payment('formatCardExpiry');
$('.cc-cvc').payment('formatCardCVC');
}
You can check if a function exists using window
For example
var fn = window['NameOfTheFunction'];
if(typeof fn === 'function') {
doSomething();
}
If your function in payment.js is part of a self contained function, you need to set it to so the window object can "see" it by adding this in your self contained function:
window.NameOfTheFunction = NameOfTheFunction;
Related
I have a constant file which I share between my node backend and frontend (.ts file)
In backend inside the file I have done something like this
if (window) {
window.redirectPaths = {
// some code
}
} else {
// something
}
For NodeJS, Since window doesn't exist, I thought it will go to else but instead it is throwing the following error
if (window) {
^
ReferenceError: window is not defined
Any help in why is this happening and how can I solve this?
use typeof window !== "undefined"
if (typeof window !== "undefined") {
window.redirectPaths = {
// some code
}
} else {
//
you want to check the window type first before accessing it.
if (typeof window === 'undefined'){
// some code
} else {
window.redirectPaths = {
// some other code
}
}
You can check this way
if (typeof window !== 'undefined' && window){
window.redirectPaths = {
// some other code
}
} else {
// some code
}
In Node.js environment it is called global object. So you can write global instead of window
you could use try catch
try {
window.redirectPaths = {
// some code
}
} catch (err) {
// something else
}
I am developing a site using a third-party CMS and I have to include functions across various parts of the content depending on which page is being displayed. To reduce the amount of functions being called on each page load, I would like to loop through an array of functions to check if they exist before firing them.
This single function would then be called at body onload.
I have adapted code from Javascript Array of Functions and How to implement an array of functions in Javascript? as well as isFunction.
My understanding was that I could put the functions in an array without () and they would not be called but in my console in Chrome an Uncaught Reference error is generated on the line in the array where a function name is mentioned.
e.g. the jb_underimage_height function is not in the code on all pages, so this generates the error when it does not exist.
Here is the code so far:
function jb_onloads() {
var functionArray = [
jb_category_price_POA,
jb_highlight_tech_columns,
jb_underimage_height,
jb_moveGuestButton,
jb_loginCheck,
jb_moveRefineSpan,
jb_style_from_url,
materials_dropdown,
jb_remove_search_spaces,
jb_init_social,
checkCookies,
jb_category_change_class,
jb_move_basket_text,
jb_style_form,
jb_checkNotifyEnvelope
]; // end of functionArray
$.each(functionArray, function(key, value) {
if(typeof functionArray[key] !== 'undefined' && typeof functionArray[key] === "function") { functionArray[key](); }
});
} // end of jb_onloads
And this was my workaround when I had to this.
function a() { alert ("I am a") };
function b() { alert ("I am b") };
var arr = [
typeof a === "function" && a || 0,
typeof b === "function" && b || 0,
typeof c === "function" && c || 0
];
arr.forEach(function(func) {
if(typeof func === "function") {
func();
}
});
maybe we can do it as:
1 function defining:
if (typeof myFuncCollections == "undefined") // window.myFuncCollections
myFuncCollections = {};
myFuncCollections.func1 = function func1() {
console.log("func1");
};
//or
myFuncCollections['funcname'] = function funcname() {
console.log("funcname");
}
....
2 jb_onloads()
function jb_onloads() {
if (typeof myFuncCollections == "undefined")
myFuncCollections = {};
$.each(myFuncCollections, function(i) {
myFuncCollections[i]();
});
}
3 call jb_onloads() after including 1 and 2. And That do not require inlcuding 1-script before 2-script. Also, your can use any function in 1-script outside jb_onloads after including 1-script.
Since using Global value, please use special prefix for naming your "myFuncCollections"
You are trying to insert function references to the array. But if the function is not defined then that name does not exists and thus the error.
Add them as strings
function jb_onloads() {
var functionArray = [
'jb_category_price_POA',
'jb_highlight_tech_columns',
'jb_underimage_height',
'jb_moveGuestButton',
'jb_loginCheck',
'jb_moveRefineSpan',
'jb_style_from_url',
'materials_dropdown',
'jb_remove_search_spaces',
'jb_init_social',
'checkCookies',
'jb_category_change_class',
'jb_move_basket_text',
'jb_style_form',
'jb_checkNotifyEnvelope'
]; // end of functionArray
$.each(functionArray, function(index, functionName) {
// assuming functions are in the global scope
var func = window[ functionName ],
funcType = typeof func;
if (funcType === "function") {
func();
}
});
} // end of jb_onloads
I'm passing parameters to a function in a JavaScript library I wrote:
ffff.setup({
'size':{'width':'100','height':'100'}
});
In the function, I pick them up:
var ffff = {
setup: function(config) {
if (config["size"]["width"]) {my_width = config["size"]["width"];}
if (config["size"]["height"]) {my_height = config["size"]["height"];}
}
}
My error is, if I do not specify a parameter, I get a Cannot read property 'height' of undefined error: (the error occurs on if (config["size"]["height"]))
ffffr.setup({
'size':{'width':'100'}
});
How should I detect if a variable has been provided or not?
There may be more elegant approaches to this (such as jQuery extends() if you use that library), but at a very basic level you could just do
if(typeof config['size'] !== "undefined" && typeof config['size']['height'] !== "undefined")
If you are looking at the config object, you can use .hasOwnPropertyMDN
if( config.hasOwnProperty("propName") ){
//use config.propName
}
if (config.size && config.size.width) ...
Try:
if (typeof variable === 'undefined') {
// variable is undefined
}
Or:
if (typeof (conf) === 'object') {
// object is undefined
}
You could use
config["size"].hasOwnProperty('width')
Check if it is defined, and use a ternary operator to set a default
(param===undefined)?default_value:param;
what that will do is check if it is defined, and set it to whatever you want it to if it is undefined, but keep it the same otherwise
I have found similar questions about creating functions with optional parameters. But I continually run into errors is the parameter may not exist. I have an interactive map that is doing a bunch of things. However if outputlayer is null, the function will not execute. This layer may or may not exist. I just can't seem to figure out how to pass this optional parameter in if it doesn't exist. Thanks for any help!
function appdelete(selected,vectorlayer,drawFeature,outputlayer) {
$(selected).prev().children().children().eq(2).val('Latitude');
$(selected).prev().children().children().eq(4).val('Longitude');
vectorlayer.destroyFeatures();
drawFeature.activate();
try {
map.removeLayer(outputlayer);
} catch(err) { };
}
Check if it exists first and maybe the type.
if(outputlayer && "object" === typeof outputlayer) {
map.removeLayer(outputlayer);
}
You will need to check if the variable exists:
if(outputlayer){
map.removeLayer(outputlayer);
}
If you only care undefined, do this:
if(outputlayer === undefined) return;
or
if(outputlayer !== undefined) {
map.removeLayer(outputlayer);
}
Default parameter initialyzing:
outputlayer= (typeof outputlayer=== "undefined") ? "someDefaultValue" : outputlayer;
In your function:
function appdelete(selected,vectorlayer,drawFeature,outputlayer) {
outputlayer= (typeof outputlayer=== "undefined") ? "defaultValue" : outputlayer;
$(selected).prev().children().children().eq(2).val('Latitude');
$(selected).prev().children().children().eq(4).val('Longitude');
vectorlayer.destroyFeatures();
drawFeature.activate();
map.removeLayer(outputlayer);
}
I found how to call actionscript from javascript, but I need to pass some arguments too (dynamic),how can I do this?
TIA.
Please, try this:
ExternalInterface.addCallback("sendMsg", generateMsg);
function generateMsg(str):void {
trace(str);
}
JS:
msg = "";
function setMsg(myMsg) {
msg = myMsg;
SendDataToFlashMovie(myMsg);
}
In my experience you have to call the function on the flash object.
I use the following javascript function to get the flash object
function GetSWF(id) {
if (window.document[id] != null)
if (window.document[id].length == null)
return window.document[id];
else
return window.document[id][1];
else
if (typeof(document[id]) == 'undefined')
return $('#'+id)[0];
else
if (document[id].length == null)
return document[id];
else
return document[id][1];
}
then call the function as follows
var flash = GetSWF('idOfSWF');
if (typeof flash.sendToActionScript === 'function'){
flash.sendToActionScript(yourObject,orParameter);
}
the AS3 would look like follows
if (ExternalInterface.available){
ExternalInterface.addCallback("sendToActionScript",receivedFromJavascript);
}
function receivedFromJavascript(myObject:Object,myParameter:String):void{
// Do something
}
Hope this helps.
EDIT:
Just noticed that I have a small usage of jQuery in the GetSWF function. I'll take a look and try and remove that. (Its the line return $('#'+id)[0];)