Javascript: Proper closure syntax and formatting - javascript

I am only moderately experienced with JS/jQuery. I am attempting to parse an XML object that I retrieved from IIS, here's some pseudocode that roughly describes my problem:
//accepts an XML Object
function dataFromAjax(object) {
var x; // this is an int used to ID the object
var y;
var z;
var arr = [];
var __data = this;
var xmlObject = object;
function readDataFromXMLObject() {
__data.x = $(xmlObject).find("X").text();
__data.y = $(xmlObject).find("Y").text();
__data.z = $(xmlObject).find("Z").text();
testArr = $(xmlObject).find("TestArrInfo").text().split(",");
if(testArr[0] != null)
__data.arr.push(testArr[0]);
// ...
}
function storeData() {
sessionStorage.setItem(__data.x, JSON.stringify(__data));
}
readDataFromXMLObject();
storeData();
}
In the console it gives me the following error while attempting to parse arr[]:
Uncaught TypeError: Cannot read property 'push' of undefined
When I try manually typing something like sessionStorage.getItem(123) (with and without quotes) it also returns null.
To test the values, I tried both console.log(xmlObject) and console.log(__data.x) for debugging, those worked fine and gave me the XML object and value of x, respectively. Not sure why the array isn't working or why the whole object doesn't save. I'd greatly appreciate any hints.

In this scope you can access to arr directly:
arr.push(testArr[0])
Your this context probably points to window object. window.arr is undefined.
Read about this context in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Related

Creating property for an object during run time

I am trying to create a property for an object like shown below but if I type Object.keys(window.data) I am getting the object name as DENTAL[object Object]
Method goes like this:
function GetAppliedFilterValue(TabName, filter) { //TabName="DENTAL", filter.CoverageId = 10
var property = TabName.concat(String(filter.CoverageId));
window.data[property.toString()] = {};
Where am I going wrong?
PS. the coverageId property of object filter is Number type
Thank you #Bergi, your suggestion helped me that worked.
My implementation:
function GetAppliedFilterValue(TabName, filter) {
var property = TabName + String(filter.CoverageId);
window.data[property.toString()] = {};

How to get the "typeof" in JavaScript for a json message

When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];

Unexpected string from Chrome storage set

I'm trying to set in localStorage after checking if the key already exists, but I'm getting this error. Anyone know what is happening and how can I solve it?
chrome.storage.sync.get($div.attr('id'),function(items){
var lastError = chrome.runtime.lastError;
if (lastError) console.log($div.attr('id')+" does not exist.\n", lastError);
else chrome.storage.sync.set({$div.attr('id'):$div.html()}, function(){}); //I'm having the error from this line
});
Uncaught SyntaxError: Unexpected string
Edit:
Apparently this has something to do with the attr('id')
because I created a variable and then the problem was gone. Thank you anyway.
This is working:
var myobj = {}, key = $div.attr('id');
myobj[key] = $div.html();
chrome.storage.sync.get(key,function(items){
var lastError = chrome.runtime.lastError;
if (lastError) console.log(key+" does not exist.\n", lastError);
else chrome.storage.sync.set(myobj, function(){}); //The error is gone
});
The problem isn't with attr itself, but in the way you're trying to dynamically set a key on a new object literal using it:
{$div.attr('id'):$div.html()}
You can't create an object literal in this way. Keys in the creation of an object literal must be string or numeric literals.
To attach a dynamic key to an object you'd rather do something like this:
else {
var obj = {}, key = $div.attr('id');
obj[key] = $div.html();
chrome.storage.sync.set(obj, function(){});
}

javascript wierdness returning value

Hi I am new with javascript, there is a problem that is driving me crazy:
what is the difference between an object staticly declared as this one :
{$or:[{tc_clpar_id:4,tc_par_id:{$in:[79,80]}},{tc_clpar_id:5,tc_par_id:{$in:[105,106]}}]}
and an object costruct at run-time, with this function:
function buildQuery(self,setting,query){
var query = {$or:[]};
cl = 'tc_cl'+self.family+'_id';
att ='tc_'+self.family+'_id';
keys = Object.keys(setting);
for( var k=0;k<keys.length;k++){
ch = keys[k];
var q = {};
q[cl] = ch;
q[att] = {$in:setting[ch]};
query.$or.push(q);
}
return query;
this object is used as query for the node-mongodb-native driver, the first one works, the object return by the function in correct, I checked the two object with assert.deepEqual, there are no errors, but using the produced object I get an empty resultset, I do not have any clue about the problem, I thought maybe something strange with the scope as the function is a method of another object, or maybe with the garbage collector.

got stuck with this set of code in jquery validate

var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop.
The formRules string will have these options comma seperated and the corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
change this line
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
to this
$.validationEngine.defaults[rulesArray[i]] = valuesArray[i];
rulesArray is not a child of $.validationEngine.defaults. The values stored in your rulesArray are. The syntax in my second code block references everything properly.
This is called Bracket Notation, a way to get an object's property using any sort of valid calculation (like rulesArray[i], or "myStringPropertyName"). see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators for other methods.

Categories