I can't for the life of me figure out how to do this. I have my jquery name spaced a certain way in that it is prefixed with NWO.{function-name} to make it a little more organized. So it looks something like this:
var NWO = NWO || {}
NWO.Chat = (function() {
return{
init : function($objects) {
console.log('do something');
} }
}
}());
jQuery(document).ready(function(){
NWO.Chat.init($('div').find('a.chat'));
});
Now the chat element isn't on every page so on certain pages where the chat link doesn't exist I get a NWO.Chat is undefined. I thought for the pages that don't have the chat link I could do something like this to avoid the error.
if(jQuery().NWO.Chat){ NWO.Chat.init($('div').find('a.chat')); }
or
if($.fn.NWO.Chat){ NWO.Chat.init($('div').find('a.chat')); }
But neither seems to be working I still get the error. How do I avoid the js error when the chat link isn't on the page. I've been banging my head for hours. Thanks in advance.
NWO is not a jQuery plugin so have nothing to do with jQuery, it is a object(looks like a global scope), so you could just do
if (NWO && NWO.Chat && typeof NWO.Chat.init == 'function') {
NWO.Chat.init($('div').find('a.chat'));
}
You can use typeof to check if the object is defined or not by comparing it with "undefined"
if(typeof NWO.Chat != 'undefined')
You can also just fix the root of your problem:
NWO.Chat = (function() {
return{
init : function($objects) {
console.log('do something');
} }
} // <<-----------REMOVE THIS CURLY BRACE
}());
That extra curly at the end (}) is the issue.
Related
I'm new to using react.js, and am trying to write a re-usable component that has an optional property passed to it. In the component, that optional property pulls data from a db using meteor, then I want to check if a property exists on the returned object (parent_task exists on task), and if exists, adds a link. This seems fairly simple, but I keep getting errors. Does anyone have any suggestions on what I might be missing? Is there a jsx gotcha that I'm missing?
<Header task={params.task_id} /> // rendering component with property
// Task List Header
Header = React.createClass({
mixins: [ReactMeteorData],
getMeteorData() {
var handle = Meteor.subscribe('tasks');
return {
taskLoading: ! handle.ready(),
task: Tasks.findOne({_id: this.props.task})
}
},
getParentTaskLink() {
if (!this.data.taskLoading) {
var current_task = this.data.task;
if (parent_task in current_task) { // or current_task.hasOwnProperty(parent_task)
console.log("parent_task exists!");
}
}
},
render() {
return (
<div className="bar bar-header bar-calm">
{this.getParentTaskLink()} // eventually return anchor element here
<h1 className="title">Hello World</h1>
</div>
)
}
});
what is the prop in question? how about
{this.props.propInQuestion ? link : null}
I figured this out. Apparently it was a syntax issue - you need to use a string when searching for properties in objects. The line below works:
if ('parent_task' in current_task)
For me works:
if ('myProperty' in this.props) {}
or
if (this.props.myProperty !== undefined) {}
or
if (this.props.hasOwnProperty('myProperty')) {}
Next condition will not work for number property, as 0 value will not work (such as for empty string):
if (this.props.MaxValue) {}
Check if a property exists using React.js
There are two options you can use. the && operator and If statement to check if the props exist.
Option 1 will check if the property exists then run the second part of the code. It works like an if without the if.
Option 1
this.props.property && this.props.property
Option 2
if(this.props.property){
this.props.property
}
This also works with function names.
You can use this also check to render components and tags.
This works for me
if(this.props.test === undefined){
console.log('props.test is not defined')
}
I suggest to try this elegant solution to check callback property on your component:
if(typeof this.props.onClickCallback === 'function') {
// Do stuff;
}
or applying destructuring:
const { onClickCallback } = this.props;
if(typeof onClickCallback === 'function') {
// Do stuff;
}
The most upvoted answer
props.propInQuestion ? 'a' : 'b'
Doesn't work if the prop is a boolean and you're trying to check for existence.
Based on How do I check if an object has a key in JavaScript? the fastest way is props.hasOwnProperty('propInQuestion'), with the caveat that this will not search the prototype chain.
In functional components, you can use like this.
if(props.myProperty){
//do something
}else{
//do something
}
if(props.hasOwnProperty('propertyName')){
//do something
} else {
//do something else
}
You need to return out of getParentTaskLink() with the link you need.
if (current_task.parent_task) {
return (link);
} else { return null; }
I want to find some variable from 2 different element patterns.
var something = $('.class').attr('data-something');
if(typeof something === 'undefined') {
var something = $('.class').attr('data-another');
}
if(typeof something != 'undefined') {
// do action...
console.log(something);
}
I just want to get some data from attr data-someting="mydata"
And if data-someting="mydata" not found so find a data form data-another
Then do action....
Im doing right ? or another correctly way to do better ?
Whats about Try Catch ?
Some browsers will have it undefined while some will return false. So, here is a more robust version:
if (typeof something === 'undefined' || something === false) {
// try another attribute
} else {
// do your stuff
}
Update:
Hm, accroding to the doc:
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set.
So, probably, they are explicitly ensuring this themselves as of 1.6 and my information about false is outdated. In this case your own code is perfectly correct.
You can/should access data properties using $.data();
e.g
var something = $('.class').data('something');
var something = $('.class').attr('data-something') || $('.class').attr('data-another')
This will do for both undefined and false values
i am sending FB.login request to facebook. but FB is not defined while javascript SDK is still loading core javascript resources.
so, i put a check to get FB variable
function check_FB_variable(){
if(typeof FB=='undefined'){
check_FB_variable();
}else{}
}
check_FB_variable();
But this approach gives me Too much recursion error.
so , i put this code as
function check_FB_variable(){
if(typeof FB=='undefined'){
setTimeout(check_FB_variable,600);
}else{}
}
check_FB_variable();
but in this approach the before timeout function make a call function moves down and gives error
FB.login not defined.
please, help.
I've used something similar to check if JQMobi exists, I don't know exactly why but I think the exception is thrown because you call the pointer to the function every time.
You should try checking in an interval like this (Untested):
var facebookChecker = window.setInterval(fbCheck, 200);
var fbCheck = function () {
if (typeof FB != 'undefined' && facebookChecker != null) {
window.clearInterval(facebookChecker);
facebookChecker = null;
// Whatever you want to do if facebook is loaded
// Example: InitFBLogin();
}
}
Or you could use a while statement (the one I used):
/*
* This JQ Fix tries to attach Jquery to a variable to ensure it exists.
* - Marvin Brouwer.
*/
var FixJQ = function () {
var JQFIX = null;
while (!JQFIX || JQFIX == null) {
try {
JQFIX = jQuery;
} catch (nothing) { jQuery = $; };
};
JQFIX = null;
return true;
};
if (FixJQ()) {
FixJQ = null;
};
The beauty of the last one is that you can put you next step below this, because it will wait until the while loop has finished.
I honestly do not know which one is better/faster but I’m sure the bottom one will work.
I only want my JavaScript to run once, but I cannot control how many times the javascript file is executed. Basically I'm writing a tiny JS snippet into a CMS, and the CMS is actually calling it 5-10 times. So solutions like this:
function never_called_again(args) {
// do some stuff
never_called_again = function (new_args) {
// do nothing
}
}
never_called_again();
Don't seem to work because as soon as my snippet is run again from the top the function is re-declared, and 'do some stuff' is re-evaluated. Perhaps I'm just not doing it properly, I'm not great with JS. I'm considering using something like try-catch on a global variable, something like
if (code_happened == undefined) {
\\ run code
code_happened = true;
}
EDIT: There is a consistent state e.g. if I set a variable I can see when my snippet is run again. But having to declare it before I access it, I don't know how to say 'does this variable exist yet'
Try this:
var doneTheStuff;
function whatever() {
if (!doneTheStuff) {
doneTheStuff = true;
// do the stuff
}
}
Redundant variable declarations don't affect the value of the variable. Once one of the functions has set the variable to true, the others won't do anything.
if (typeof code_happened === 'undefined') {
window.code_happened = true;
// Your code here.
}
The typeof check gets you around the fact that the global hasn't been declared. You could also just do if (!window.code_happened) since property access isn't banned for undefined properties.
Use a closure, and set a flag. If the flag is true, just return:
if ( ! window.never_called_again ) {
window.never_called_again = (function () {
var ran = false;
return function (args) {
if ( ran ) return;
ran = true;
// Do stuff
};
}());
}
Here's the fiddle: http://jsfiddle.net/U2NCs/
With jQuery, the function .one() may be useful : http://api.jquery.com/one/
W3School exemple here : http://www.w3schools.com/jquery/event_one.asp
In this way, the code is executed only once.
if(typeof onceRun == "undefined") window.onceRun=(
()=>{
//your codes...
console.log("runing...")
return true
}).call()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery test for whether an object has a method?
I want to set if Function Exists before Calling javascript can you help me how do this and apply on this script
$(document).ready(function() {
$(".cs-text-cut").lettering('words');
});
I'm assuming that you're wanting to check and make sure that lettering exists, try this:
http://api.jquery.com/jQuery.isFunction/
Here's an example:
if ( $.isFunction($.fn.lettering) ) {
$(".cs-text-cut").lettering('words');
}
Use this to check if function exists.
<script>
if ( typeof function_name == 'function' ) {
//function_name is a function
}
else
{
//do not exist
}
</script>
If it's the lettering function you want to test for, you can do so like this;
$(document).ready(function() {
var items = $(".cs-text-cut");
if (items.lettering) {
items.lettering('words');
}
});
Or, if you want to make absolutely sure items.lettering is a function before attempting to call it, you can do this:
$(document).ready(function() {
var items = $(".cs-text-cut");
if (typeof items.lettering === "function") {
items.lettering('words');
}
});
Or, if you really don't control the environment so you don't really know if the lettering function call is going to work or not and might even throw an exception, you can just put an exception handler around it:
$(document).ready(function() {
try {
$(".cs-text-cut").lettering('words');
} catch(e) {
// handle an exception here if lettering doesn't exist or throws an exception
}
});
typeof $({}).lettering == 'function' or $.isFunction($({}).lettering) should return a boolean for whether it's available yet or not.