angular json related functions against native js - javascript

angular.toJson( obj, pretty );
angular.fromJson( json );
vs
JSON.stringify( obj )
JSON.parse( json )
I used to use native ones, but started to use angular ones for consistency. Any other reasons to use those?

My first thought was it's related to some test purposes(same case with using $window instead of window). But after looking into source code: https://github.com/angular/angular.js/blob/master/src/Angular.js#L977
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
Looks like it's a simple wrap for case with undefined object as param.
same for fromJson: https://github.com/angular/angular.js/blob/master/src/Angular.js#L998
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
so, generally, it's just to remove that checking from app code into framework code.

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

angular.isDefined() vs obj.hasOwnProperty()

I have an object that may or may not have a status. When using the angular.js framework which would be more appropriate. What are the advantages and disadvantages of both.
var checkStatus = function(item){
if(angular.isDefined(item.status){
//do something
}
//VS.
if(item.hasOwnProperty('status')){
//do something
}
}
checkStatus(item);
angular.isDefined only test if the value is undefined :
function isDefined(value){return typeof value !== 'undefined';}
Object.hasOwnProperty test if the value is a direct one and not an inherited one.
For example :
var test = {};
angular.isDefined(test.toString); // true
test.hasOwnProperty('toString'); // false
info : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Cache is not defined error

function example(str) {
var cache = ( str != "" ) ? str : null;
}
example("something");
alert(cache); // cache is not defined
On alert, it says cache is not defined. How to make it so that after calling a function, cache will be saved and I could invoke it like alert(cache).
The variable 'cache' is defined in the function example and not outside that scope so alert does not have access to it. Please look at other similar questions, example: https://stackoverflow.com/questions/22113894/variables-from-anonymous-function/22114051#22114051 ; not 10 minutes ago. I would also recommend reading on Javascript especially how variable scope works. It is very similar to most programming languages but funky in a couple other, ex: http://msdn.microsoft.com/en-us/library/bzt2dkta(v=vs.94).aspx
Not recommended, but a quick answer is:
var cache;
function example(str) {
cache = ( str != "" ) ? str : null;
}
example("something");
alert(cache);
cache is a local variable to example function. I suggest to use a namespace instead of a global variable. If it wont be a global variable, be free to use a classic var declaration.
so:
var app = app || {}; //define namespace
app.cache = "";
function example(str) {
app.cache = str != "" ? str : null;
//i guess it should equal to:
// cache = str ? str : null;
}
console.log(str); //similar to alert, but logs in developers tool (chrome) or firebug(FFx)
ps: I suggest the use of console.log() (or debug) instead of alert(). It's more comfortable than alert()
Self-memorizing functions
Memorization is the process of building a function that’s capable of
remembering its previously computed values. This can markedly increase
performance by avoiding needless complex computations that have
already been performed.
function foo(str) {
if (!foo.cache) {
foo.cache = ( typeof str !== undefined ) ? str : null;
}
}
foo("something");
alert(foo.cache);
Define cache outside function exmaple()
var cache;
function example(str) {
cache = ( str != "" ) ? str : null;
}
When you define inside the function it's scope would be finished inside it, so you can not access cache from outside of function in your case.

Correctly way to find some variable with 2 case

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

Categories

Resources