Correctly way to find some variable with 2 case - javascript

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

Related

OOP Question About Vanilla JS: The class's constructor won't accept the variable I'm feeding it as a parameter

I'm trying to learn OOP through practice, but I'm pretty stuck at this point.
This is the code:
const itemEdit = () => {
let editIndex = buttonObj.editArr.indexOf(editID);
console.log(`the editIndex outside of the class is ${editIndex}`);
if (typeof editIndex != "undefined") {
editText = new htmlTextualizer(editIndex);
console.log(
"new class successfully created as variable is not 'undefined' type"
);
}
editText.printOut();
This is the class/constructor:
class htmlTextualizer {
constructor(curr) {
this.curr = curr;
}
printOut() {
console.log(this.curr);
}
}
The output is either 'undefined' or nothing at all. The logic generally works outside of the function, so I suspect it's something to do with the scope of initiation, but I simply fail to work my way around it. Assistance would be much appreciated. Thanks.
JavaScript's indexOf() returns -1 if no match is found. That check should look something like this:
if (editIndex > -1) {…}
I'm not sure if that will resolve your problem or not, but it's a problem in general.
Also, if that if statement is not true, and if editText is not defined somewhere outside what you've pasted here, there will be an error because editText is undefined (and doesn't have methods available).
There are several things that are unclear about your example, since you reference several undefined objects: buttonObj.editArr, editID, editText.
In general, I would approach testing for existence more carefully. You don't want to attempt to access the indexOf method on something undefined.
I'm not sure what your business logic is exactly, but here is how to do what I think it is: always create the new object, unless buttonObj.editArr contains editID.
Here is how to do that:
const itemEdit = () => {
if ( !buttonObj ||
!buttonObj.editArr ||
(typeof buttonObj.editArr !== "object") ||
!editID ||
(buttonObj.editArr.indexOf(editID) < 0) ) {
editText = new htmlTextualizer(buttonObj.editArr.indexOf(editID));
console.log("creating instance of class htmlTextualizer");
}
}

Check if property exists using React.js

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

Check if Function Exists before Calling? [duplicate]

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.

Is there a way to do function overloading in Javascript?

I have code that looks like this:
function getTopicOptions(accountID, showTitles, showSelectGroup) {
"use strict";
var accountID = store.getItem('AccountID');
showTitles = (showTitles !== 'undefined') ? showTitles : 'Y';
showSelectGroup = (showSelectGroup !== 'undefined') ? showSelectGroup : 'Y';
The idea is that if showTitle and showSelectGroup are not supplied then they will get the default of "Y".
Is there a way do this with function overloading or a way to have the function parameters checked (jslint?) or a way to simplify what I need to do without the undefined check?
You could do something like this:
showTitles = showTitles || 'Y';
or this would work as well, but is more verbose
showTitles = showTitles ? showTitles : 'Y';
I'm not sure where function overloading comes into your question.
There is popular default params trick:
var showSelectGroup = showSelectGroup || false;
but it depend on param, if it bool ('', 0 and etc) and looks like showSelectGroup || true you can't set false
Also look at:
Set a default parameter value for a JavaScript function [closed]
Is there a better way to do optional function parameters in
Javascript?
EDIT
Following is possible
var functionTest = function(argu) {
argu = argu || 'my argument';//ifargu not passed than 'my argument'
return argu;
};
alert(functionTest());
// browser alerts "my argument"
There is no way of function overloading in javascript ,
But if you dont pass the vlaue in function its became undefined vlaue that means you can call the function like
this function
getTopicOptions(accountID, showTitles, showSelectGroup)
can be called like
getTopicOptions(1);
other two value becomes undefined.
There is an arguments object which is (more or less) an array of all supplied arguments. You can loop through these.
See http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/

Overriding a Javascript method only if it does not exist

My goal here is to override a method if it isn't found, otherwise use the original method (for backwards compatibility of a library I can't alter).
This is what I have so far, but am still struggling with:
this.grid.getDataSource = function(){
if (typeof this.grid.getDataSource.getDataSource == "undefined")
return this.grid.getDataSource.getStore();
else return this.grid.getDataSource.getDataSource();
}
I want to have getDatasource() check if it exists, if not, call getStore(). If it does exist, just use the original getDatasource(). I know this breaks because I haven't figured out how to reference the parent 'this' scope. When I work around that issue I get into a recursive loop as it keeps trying to override itself. If you have a better way of doing this please let me know!
i think this should do what you want.
this.grid.getDataSource =
this.grid.getDataSource.getDataSource || this.grid.getDataSource.getStore;
this statement will try to find something that evaluates truish from left to right. when it finds that thing, it will use it as the value for the assignment. in this case if getDataSource is undefined it'll evaluate as false, and getStore will be checked. getStore exists so it'll evaluate to (roughly) true, and so the function reference will be assigned to this.grid.getDataSource.getDataSource;
If you're sure that getDataSource() will not throw an exception, you can try
this.grid.getDataSource.getDataSource = function(){
try {
return this.getDataSource();
}
catch(ex) {
return this.getStore();
}
};
or you can just change
if (typeof this.getDataSource == "undefined")
to
if (typeof this.getDataSource != "function")
UPDATE:
Does this work?:
this.grid.getDataSource = function(){
if (typeof this.getDataSource != "function")
return this.getStore();
else
return this.getDataSource();
}

Categories

Resources