How to retrieve Firebase's child's value into global scope? - javascript

I have a Firebase database set up like this:
>>XXX
>>>>dislike: 0
>>>>like: 1
In my web application, I can retrieve their value into console by:
var fb = new Firebase('https://xxx.firebaseio.com');
fb.child('like').once('value',function(snapshot){
console.log(snapshot.val());
});
fb.child('dislike').once('value',function(snapshot){
console.log(snapshot.val());
});
Now if I want to retrieve these values into the global scope, it will return undefined when I do this:
var fb = new Firebase('https://xxx.firebaseio.com');
var like = fb.child('like').once('value',function(snapshot){
return snapshot.val();
});
var dislike = fb.child('dislike').once('value',function(snapshot){
return snapshot.val();
});
Of course I have a silly solution to this problem, by putting entire script inside these two scopes - but it would be a disasters if I have hundreds of scopes to work with, and if I like to dynamically turn them on and off. Here is my solution:
var likeRef = new Firebase('https://xxx.firebaseio.com/like');
var dislikeRef = new Firebase('https://xxx.firebaseio.com/dislike');
likeRef.once('value',function(likeObj){
dislikeRef.once('value',function(dislikeObj){
var like = likeObj.val();
var dislike = dislikeObj.val();
});
});
Here is another answer suggested by Frank van Puffelen from the source <Passing variable in parent scope to callback function>, and it didn't quite work because seem to only work for script that is adding a new object in an array. Here is my attempt:
var like = 0;
var dislike = 0;
var val = 0;
var fb = new Firebase('https://xxx.firebaseio.com/');
function fb_like() {
fb.child('like').on('value', read_val);
return val;
}
function fb_dislike() {
fb.child('dislike').on('value', read_val);
return val;
}
function read_val(snapshot) {
var val = snapshot.val();
}
fb_like();
fb_dislike();
console.log(like);
console.log(dislike);
As you might expected, the console logs 0 and 0, instead of the values in like and dislike in firabase xxx database.
In fact, I took a step further and use array instead of integer value, and it still won't work:
var like = [0];
var dislike = [0];
var val = [0];
var fb = new Firebase('https://xxx.firebaseio.com/');
function fb_like() {
fb.child('like').on('value', read_val);
console.log('fb_like: ' + val[0]);
return val;
}
function fb_dislike() {
fb.child('dislike').on('value', read_val);
console.log('fb_dislike: ' + val[0]);
return val;
}
function read_val(snapshot) {
val[0].value = snapshot.val();
}
fb_like();
fb_dislike();
console.log('Like: ' + like[0]);
console.log('Dislike: ' + dislike[0]);
The console will logs:
fb_like: 0
fb_dislike: 0
Like: 0
Dislike: 0
This means probably means only adding (pushing) new objects into an array will work on a global scope, changing the value of an object will only effect the local scope.
Then, I realized even adding (pushing) new objects into an array cannot effect the global scope. Here is my attempt:
var like = 0;
var likeObj = [];
var fb = new Firebase('https://xxx.firebaseio.com/');
function fb_like() {
fb.child('like').on('value', read_like);
console.log('fb_like: ' + likeObj[0]);
return likeObj;
}
function read_like(snapshot) {
likeObj.push(snapshot.val());
console.log('likeObj: ' + likeObj[0]);
}
fb_like();
like = likeObj[0];
console.log('Like: ' + like);
As a result, the console logs:
fb_like: undefined
Like: undefined
likeObj: 1
This probably means the read_like() isn't effecting scopes larger than itself, event with array.push command.

Related

.map() unable to access Object's this.function

Thanks in advance for any responses:
I don't think this is a duplicate: I reviewed that article in the first comment, that is just a general breakdown of objects and using "this" within javascript.
My other this.function's perform just fine, so I at least have the basics of JS Obj's figured out.
This issue is related to using .map() with a this.function within a constructed object.
The following Google Appscript code uses .map() to update a string in a 2d array. [[string, int],[string, int]]
For some reason, when using .map() it is am unable to access the function "this.removeLeadingZero". If that same function is placed outside of the OBJ it can be called and everything works just fine. For some reason the system claims row[0] is an [object, Object] but when I typeof(row[0]) it returns "string" as it should.
Error: TypeError: Cannot find function removeLeadingZero in object [object Object]. (line 106, file "DEEP UPC MATCH")
Is there any issue using this.function's with .map() inside an object or am I using an incorrect syntax?
function test2DMapping(){
var tool = new WorkingMappingExample()
var boot = tool.arrayBuild();
Logger.log(boot)
}
function WorkingMappingExample(){
this.arr= [["01234", 100],["401234", 101],["012340", 13],["01234", 0422141],["01234", 2],["12340",3],["01234", 1],["01234", 2],["12340",3],["01234", 1],["01234", 2],["12340",3],["01234", 1],["01234", 2],["12340",3]];
//mapping appears faster that normal iterations
this.arrayBuild = function(){
var newArray1 =
this.arr.map( function( row ) {
**var mUPC = removeLeadingZero2(row[0])** //working
**var mUPC = this.removeLeadingZero(row[0])** // not working
var index = row[1]
Logger.log(mUPC + " " + index)
row = [mUPC, index]
return row
} )
return newArray1;
};
}; //end of OBJ
//THE NEXT 2 FUNCTIONS ARE WORKING OUTSIDE OF THE OBJECT
function removeLeadingZero2(upc){
try {
if (typeof(upc[0]) == "string"){
return upc.replace(/^0+/, '')
} else {
var stringer = upc.toString();
return stringer.replace(/^0+/, '')
}
} catch (err) {
Logger.log(err);
return upc;
}
}
function trimFirstTwoLastOne (upc) {
try {
return upc.substring(2, upc.length - 1); //takes off the first 2 #'s off and the last 1 #'s
} catch (err) {
Logger.log(err);
return upc;
}
}
Inside the function that you pass to map, this doesn't refer to what you think it does. The mapping function has its own this, which refers to window, normally:
var newArray1 = this.arr.map(function(row) {
// this === window
var mUPC = this.removeLeadingZero(row[0]);
var index = row[1];
Logger.log(mUPC + " " + index);
return [mUPC, index];
});
You have four options:
Array#map takes a thisArg which you can use to tell map what the this object in the function should be:
var newArray1 = this.arr.map(function(row) {
// this === (outer this)
var mUPC = this.removeLeadingZero(row[0]);
// ...
}, this); // pass a thisArg
Manually bind the function:
var newArray1 = this.arr.map(function(row) {
// this === (outer this)
var mUPC = this.removeLeadingZero(row[0]);
// ...
}.bind(this)); // bind the function to this
Store a reference to the outer this:
var self = this;
var newArray1 = this.arr.map(function(row) {
// self === (outer this)
var mUPC = self.removeLeadingZero(row[0]);
// ...
});
Use an arrow function:
var newArray1 = this.arr.map(row => {
// this === (outer this)
var mUPC = this.removeLeadingZero(row[0]);
// ...
});
Additionally, you could stop using this and new.
I have solved this issue and below is the answer in case anyone else runs into this:
this needs to be placed into a variable:
var _this = this;
and then you can call it within the object:
var mUPC = _this.removeLeadingZero(row[0])
Javascript scope strikes again!

Javascript variable inheritance issue

I am having an issue with some code which I would expect to work. I have a variable defined outside a function and as such would expect that to be available to the function through inheritance. I console log the variable outside the function and get a value and console log inside the function and get undefined. I have used comments in the code to show these console logs. Any help here would be great. Please see code snippet below. Thanks Ant
for (var i = 0; i < parseResult.length; i++) {
var destination = parseResult[i].attributes.userInfo;
for (var i = 0; i < firebaseResult.length; i++) {
if (firebaseResult[i].$id == parseResult[i].attributes.facebookID) {
parseResult[i].attributes.convoID = firebaseResult[i].convoID;
console.log(firebaseResult[i].time); // this returns the timestamp value
parseResult[i].attributes.lastMessage = FirebaseAPI.getLastMessage(firebaseResult[i]).$loaded()
.then(function(lastMessage) {
console.log(firebaseResult[i].time); // this returns undefined
if (!(0 in lastMessage)) {
var returnValue = 'Matched on ' + firebaseResult[i].time;
} else if (0 in lastMessage) {
var returnValue = lastMessage[0].message;
}
return returnValue;
})
.catch(function(error) {
console.log("Error:", error);
})
}
}
}
It is often not reliable to use loop iterator to access things in async callback, because when the callback come back, i would have been increased to the value that let it exit the loop.
The fix is assigning it to a variable for anything you want to hold.
console.log(firebaseResult[i].time); // this returns the timestamp value
var time = firebaseResult[i].time;
parseResult[i].attributes.lastMessage = FirebaseAPI.getLastMessage(firebaseResult[i]).$loaded()
.then(function(lastMessage) {
console.log(firebaseResult[i].time); // this returns undefined
console.log(time);
It's because you're in the callback of your FirebaseAPI.getLastMessage() call. If you log this (your scope) in it, you'll get something like a FirebaseAPI object or something.
What you can do is the classic var self = this; trick to keep your context stored in a variable accessible through scopes.
This would look like:
for (var i = 0; i < parseResult.length; i++) {
var destination = parseResult[i].attributes.userInfo;
for (var i = 0; i < firebaseResult.length; i++) {
if (firebaseResult[i].$id == parseResult[i].attributes.facebookID) {
parseResult[i].attributes.convoID = firebaseResult[i].convoID;
console.log(firebaseResult[i].time); // this returns the timestamp value
// Store your context here
var self = this;
this.results = firebaseResult[i].time;
parseResult[i].attributes.lastMessage = FirebaseAPI.getLastMessage(firebaseResult[i]).$loaded()
.then(function(lastMessage) {
console.log(firebaseResult[i].time); // this returns undefined
// Get your values
console.log(this.results); // this returns your values.
if (!(0 in lastMessage)) {
var returnValue = 'Matched on ' + firebaseResult[i].time;
} else if (0 in lastMessage) {
var returnValue = lastMessage[0].message;
}
return returnValue;
})
.catch(function(error) {
console.log("Error:", error);
})
}
}
}
I see in your tags that you're using Angularjs, so you could use the $scope object to store your scope variable and easily deal with promises and such.
Hope this helps :)

unable to change javascript object property with async, nodejs and mongodb

I have the following code:
exports.home = function(Comment,User,Activity){
return function(req, res){
var get_url = req.url.split(/\?/)[1];
if (!req.user)
{
res.writeHead(302, {
'Location': '/'
});
res.end();
return;
}
var posts_id_array = req.user.posts_id_array;
var stocks_array = req.user.watch_list;
var subscribe_to_arr = req.user.subscribe_to;
User.find({_id:{$ne:req.user._id, $nin:subscribe_to_arr}}).sort('-_id').limit(10).exec(function(err_user, users){
Activity.find({$or:[{owner_id : {$in :subscribe_to_arr}},{owner_id:req.user._id}]}).sort('-time_stamp').limit(20).exec(function(err_post,activities){
if( err_post || !activities) {
res.render('home',{user:req.user,stocks:JSON.stringify(stocks_array)});
}
else
{
var funcArr = [];
var hasPost = ["publish","comment","like"];
var notPost = ["add_stock","delete_stock"];
for(var i =0;i<activities.length;i++)
{
if(hasPost.indexOf(activities[i].type)!=-1){
var fobj = {
act: activities[i],
f:function(callback){
var test = this.act;
var comments = test.post.comments;
Comment.find({_id:{$in:comments}},function(err,_comments){
console.log("test.post.comments");
//console.log(test.post.comments);
console.log("comments ");
console.log(_comments);
console.log("type");
console.log(typeof test);
console.log("cloning obj");
// obj = JSON.parse(JSON.stringify(test)); // cloning obj
console.log(test);
console.log("setting value of comments");
**console.log(test.post.comments = _comments);** //unable to change test.post.comments
console.log("after assignment");
console.log(test.post.comments); // remain unchanged but work with obj.post.comments if I clone test as obj and use obj instead.
callback(null,test);
});
}
}
funcArr.push(fobj.f.bind(fobj));
}else{
var fobj = {
act: activities[i],
f :function(callback){
callback(null,this.act);
}
}
funcArr.push(fobj.f.bind(fobj));
}
}
async.series(funcArr,function(err,resArr){
console.log("resArr");
console.log(resArr);
res.render('home',{user:req.user,posts:JSON.stringify(resArr),stocks:JSON.stringify(stocks_array), other_users:JSON.stringify(users)});
});
}
});
}) // end of User.find
}// end of return function(req,res);
}
I want to update the post.comments property of the "test" object (see ** parts), but I was unable to do so. However, when I cloned the "test" object as "obj" then set "obj.post.comments" it works. Why is it the case? Is it because I messed up some scoping issues?
Thanks.
I have solved this problem myself. It turns out that I have store mongodb's Schema.Types.ObjectId in the test.post.comments which after some messing around I found cannot be overwritten. When I create a clone of the test object as "obj", the Schema.Types.ObjectId object in obj.post.comments is stored at a different location which allows for modification. My conjecture is that test.post.comments points to a Schema.Types.ObjectId within mongodb itself and therefore cannot be overwritten. When I create a copy of the test object, the problem is therefore resolved.
var test = this.act.concat();
use this instead.
because arrays substitution in js actually does not copy array but refer original adresses.
for example
var test = ['A','B','C','D'];
var copied = test;
test[0] = 0;
copied[1] = 0;
console.log(test) //0,0,'C','D'
console.log(copied) //0,0,'C','D'
so to avoid this issue, You can use .concat() to copy array
if you do not add anything, it will be used as copying.
var test = ['A','B','C','D'];
var copied = test.concat();
test[0] = 0;
copied[1] = 0;
console.log(test) //0,'B','C','D'
console.log(copied) //'A',0,'C','D'

Value of the variable becomes empty when accessed outside the function in node js

I have the following code :
for(var index in workload.elements)
{
var arr = [];
var resourceIdentifiers = {};
var elementinfo = {};
var metadataModified = {};
elementinfo = workload.elements[index];
arr[index] = workload.elements[index].uri;
if(workload.elements[index].parameters.imageUri)
{
arr.push(workload.elements[index].parameters.imageUri);
}
resourceIdentifiers = arr.join(',');
console.log('uri' + resourceIdentifiers);
// connects with mysql and fetch data
mysql.elementlevelpricing(resourceIdentifiers, function(result){
elementlevelpricingSummary = JSON.stringify(result,null,2);
console.log('resultin' + elementlevelpricingSummary);
});
console.log('resultout' + JSON.stringify(elementlevelpricingSummary,null,2))
}
The value of the variable elementlevelpricingSummary becomes empty as {} when accessed outside the called function mysql.elementlevelpricing().
The function passed to mysql.elementlevelpricing is an asynchronous callback, so it is actually running after the console.log line below it. You'll want to do anything you need the data for in the callback itself.

Use variable's value as variable in javascript

I have a variable with a value, let's say
var myVarMAX = 5;
In HTML I have an element with id="myVar".
I combine the id with the string MAX (creating a string myVarMAX). My question is how can I use this string to access a variable with the same name?
You COULD use eval, but if you have the var in the window scope, this is better
var myVarMAX = 5;
var id="MAX"; // likely not in a var
alert(window["myVar"+id]); // alerts 5
However Don't pollute the global scope!
A better solution is something like what is suggested in the link I posted
var myVars = {
"myVarMin":1,
"myVarMax":5,
"otherVarXX":"fred"
} // notice no comma after the last var
then you have
alert(myVars["myVar"+id]);
Since this post is referred to often, I would like to add a use case.
It is probably often a PHP programmer who gives Javascript/Nodejs a try, who runs into this problem.
// my variables in PHP
$dogs = [...]; //dog values
$cats = [...]; //cat values
$sheep = [...]; //sheep values
Let's say I want to save them each in their own file (dogs.json, cats.json, sheep.json), not all at the same time, without creating functions like savedogs, savecats, savesheep. An example command would be save('dogs')
In PHP it works like this:
function save($animal) {
if(!$animal) return false;
file_put_contents($animal.'.json', json_encode($$animal));
return true;
}
In Nodejs/Javascript it could be done like this
// my variables in NodeJS/Javascript
let dogs = [...]; //dog values
let cats = [...]; //cat values
let sheep = [...]; //sheep values
function save(animal) {
if (!animal) return false;
let animalType = {};
animalType.dogs = dogs;
animalType.cats = cats;
animalType.sheep = sheep;
fs.writeFile(animal + '.json', JSON.stringify(animalType[animal]), function (err){
if (err) return false;
});
return true;
}

Categories