I would like Create an object to store variables which I will use in my web app.
I cannot access the clientId and clientSecret from uriGetToken using this.
Also I can use the function in mApiGetToken in token.
Could you tell me what I'm doing wrong and how to fix it?
$(document).ready(function () {
// General Settings
var mApiSettings = {
clientId: 'aaa',
clientSecret: 'bbb',
token: mApiGetToken(),
uriGetToken: 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + this.clientId + '&client_secret=' + this.clientSecret
}
console.log(mApiSettings.uriGetToken);
// Get Autheticated, it requires getting a Token from HollyByte
function mApiGetToken() {
$.getJSON(mApiSettings.uriGetToken, processData);
function processData(data) {
mApiSettings.token = data.access_token;
}
//return token;
}
// For Testing
console.log(mApiGetToken());
});
The value of this is determined for the function in which it appears when that function is called.
There is no connection between the object literal in which you are using this and the value of this.
There is also no way to access a property of an object in the middle of the object literal statement that is creating it.
You need to use variables.
Although your examples don't have any special characters in them, you should make it a habit to escape any data you are inserting into a URI.
var clientId, clientSecret, mApiSettings;
clientId = 'aaa';
clientSecret = 'bbb';
mApiSettings = {
clientId: clientId,
clientSecret: clientSecret,
token: mApiGetToken(),
uriGetToken: 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + encodeURIComponent(clientId) + '&client_secret=' + encodeURIComponent(clientSecret)
}
It is a common Javascript question because this keyword doesn't behave like other OOP language like Java or C++.
The problem is:
var o = {
a : 2,
b : this.a *2
}
console.log( b ); //prints NaN because the value for this.a is undefined at the time b is being initialized
Because this is not accessible inside the object literal initialization. A workaround would be to use the name of the object instead of this:
var o = {
a : 2,
b : o.a *2
}
console.log( b ); //prints 4
Or you can define the object one-piece at a time:
var o = {
a : 2
}
o.b = o.a *2;
console.log( b ); //prints 4
Anyway your code should work if you change the mApiSettings to:
var mApiSettings = {
clientId: 'aaa',
clientSecret: 'bbb',
token: mApiGetToken()
}
mApiSettings.uriGetToken = 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + mApiSettings.clientId + '&client_secret=' + mApiSettings.clientSecret;
You can read more about the Javascript this keyword here: http://unschooled.org/2012/03/understanding-javascript-this/
EDIT:
as the other answer suggests you may want to encode your clientSecret and clientId before embedding them into the URL. If that is the case, you can use this code:
var mApiSettings = {
clientId: 'aaa',
clientSecret: 'bbb',
token: mApiGetToken()
}
mApiSettings.uriGetToken = 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + encodeURIComponent( mApiSettings.clientId ) + '&client_secret=' + encodeURIComponent( mApiSettings.clientSecret );
Related
I have this code:
<script type="module">
const _Tasks = {};
const _client = {};
const _client_simple = {};
const _status = {};
const _status_simple = {};
//need here a function to get all above declared and defined objects in a loop
</script>
I am trying to get all the above declared and defined objects in a loop.
I have tried this way:
const objects = Object.getOwnPropertyNames(this);
objects.forEach(objectName => {
console.log(objectName);
});
But this is undefined.
Is this possible and how?
JavaScript provides no mechanisms for determining what variables exist.
If you need to programmatically inspect a group of data, then you need to express that data as a group in the first place (e.g. as properties of an object that you can iterate through) instead of as individual variables.
If, on the other hand, this is just for debugging purposes, then pausing execution in the module (e.g. with a breakpoint) will cause most debugging tools to display the variables in scope.
Short answer: JavaScript has no concept of querying the list of variables defined as const or let.
You can however query the list of variables defined with var because they are attached to the window object. This is the windowKeys example below.
If you want to query the variables why not adding them to an object? This is the myObjectKeys example below.
var _Tasks = {};
var _client = {};
var _client_simple = {};
var _a_number = 123;
var _a_string = "hello";
var _a_boolean = true;
const windowKeys = Object.keys(window).filter(key => /^_/.test(key));
console.log('windowKeys:');
windowKeys.forEach(key => {
console.log(' ' + key + ', type: ' + typeof window[key]);
});
const myObject = {
_Tasks: {},
_client: {},
_client_simple: {},
_a_number: 123,
_a_string: "hello",
_a_boolean: true
}
const myObjectKeys = Object.keys(myObject);
console.log('myObjectKeys:');
windowKeys.forEach(key => {
console.log(' ' + key + ', type: ' + typeof myObject[key]);
});
Output:
windowKeys:
_Tasks, type: object
_client, type: object
_client_simple, type: object
_a_number, type: number
_a_string, type: string
_a_boolean, type: boolean
myObjectKeys:
_Tasks, type: object
_client, type: object
_client_simple, type: object
_a_number, type: number
_a_string, type: string
_a_boolean, type: boolean
This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 4 years ago.
My scenario is like this :
var data = {
name : 'joe',
message : 'Welcome ' + name,
fullname : 'Mr. ' + name
};
Expected Output :
console.log(' user : ' + data.message)
Welcome joe
How to do this ?
The probably closest approach would be to use functions as parameters.
const data = {
name: 'Joe',
message: function() {
return `Welcome ${this.name}`;
}
}
console.log(data.message())
However, keep in mind that this does not work for native JSON objects, only for JS objects.
You can define a function getter inside an object using get() and then call it as a property.
var data = {
name : 'joe',
message : 'Welcome ',
name : 'Mr. ',
get fullMessage() {
return this.message + this.name;
}
};
console.log(data.fullMessage);
You can replace message and fullname string by functions like this :
var data = {
name : 'joe',
message : function() { return 'Welcome ' + this.name },
fullname : function() { return 'Mr. ' + this.name }
}
console.log(data.message())
console.log(data.fullname())
If you want to do it in the initialization of the variable, you can do it using functions. Example:
var data = {
name : 'joe',
message: function(){
return 'Welcome ' + this.name;
},
fullname: function(){
return 'Mr. ' + this.name;
}
}
console.log('user : ' + data.message());
console.log('user : ' + data.fullname());
You could use getters:
var data = {
name : 'joe',
get message() { return `Welcome ${this.name}`; },
get fullname() { return `Mr. ${this.name}`; },
};
console.log(data.message);
console.log(data.fullname);
You can use external variable of your jSON object.
Try :
var name = "joe";
var data = {
name : name,
message : 'Welcome ' + name,
fullname : 'Mr. ' + name
};
console.log(' user : ' + data.message);
I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:
sendinvite() {
var user = firebase.auth().currentUser;
var uid = user.uid;
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
var hashKey = (snapshot.val());
console.log(hashKey)
});
var bcc = [];
for(var e in this.emailinputs){
if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("#") || !this.emailinputs[e].email.includes("."))
{
let alert = this.alerCtrl.create({
title: 'Error!',
message: 'There was an error with an email address you entered.',
buttons: ['Ok']
});
alert.present()
}else {
bcc.push(this.emailinputs[e].email);
}
}
if(bcc.length > 0) {
let email = {
bcc: bcc,
subject: 'Nudget Invite',
body: 'Join my grocery list!',
isHtml: true
};
this.emailComposer.open(email);
}
}
I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.
Edit 1
Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.
The main problem I see is that you are scoping the 'hashkey' variable to just the firebase...function(snapshot) block. This should be defined at the top near the 'uid' variable, so that all of this code can reference it.
Then in you snapshot function, remove the 'var' in front of hashkey, so it just sets the existing variable.
Also, be sure to check if 'hashkey' has a non-blank value before sending the email.
HTH,
Jim
I think the problem is here:
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
var hashKey = (snapshot.val());
console.log(hashKey)
});
You are creating the var named hashKey within an anonymous function then trying to access hashKey outside of that function.
Try the following instead:
var user = firebase.auth().currentUser;
var uid = user.uid;
var hashKey = null;
firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
hashKey = (snapshot.val());
console.log(hashKey)
});
... snip ...
body: 'Join my grocery list!',
... snip ...
This has been asked a bunch of times before but I'm not grasping it.
In the following..
var variableName = "hello";
How do I make the variable name 'variableName' based on another variable?
PHP Example
$a = 'hello';
$$a = 'hi'; // same as $hello..
echo $hello; // and $hello outputs 'hi'
I specifically need this variable variable to be used for localstorage so it may be syntax that I'm having a problem with.
What I'm Using It For (you can probbaly skip to This Seems To Work)
I want to generate a unique variable name for storing information in local storage. Variable name will be based on the post id of the wordpress post/page which I retrieve with php.
For example we will say the post id is 3333
I add the letters id to the beginning of each post id
So now I have id3333
var postIdNumber = 'id3333';
Then I get 3 other pieces of information that I want to store into local storage about this post (for simplicity I have shown an example output, not the code to get it)
var postURL = 'website.comm/a-wp-post/';
var postTitle = 'A Wordpress Post';
var postThumb = 'website.comm/images/thumb3333.jpg';
Now I want to store this information into local storage
var lsTest = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('lsTest', JSON.stringify(lsTest));
That works fine. Except that I want to be able to store multiple posts into local storage to retrieve later from a 'my favourite posts' page.
So I need a dynamic variable name.
For post ID 3333 I need the variable currently named lsTest to be named id3333
For post ID 4444 I need the variable currently named lsTest to be named id4444
This seems to work (Though I dont fully comprehend it)
solution modified from https://stackoverflow.com/a/5187652/3377049
var variableVariable = {}
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
jQuery('.test-div').text(variableVariable[vv]); // outputs id3333
While this does not..
var variableVariable = {} // also, should this have a ';' ?
variableVariable.postNumber = 'id3333';
var vv = 'postNumber';
var variableVariable[vv] = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('variableVariable[vv]', JSON.stringify(variableVariable[vv]));
In PHP I could maybe do something like this.. (for examples sake i'm mixing php variables into JS)
$uv = 'id3333';
$$uv = { 'lsURL': postURL, 'lsTitle': postTitle, 'lsThumb': postThumb };
localStorage.setItem('$$uv', JSON.stringify($$uv));
You just need to create an object of objects, keyed off of the unique post id. But then you need to stringify the object before storing it, and parse it when retrieving it.
function saveObject(key, object) {
object = JSON.stringify(object);
window.localStorage.setItem(key, object);
}
function getSavedObject(key) {
var saved = window.localStorage.getItem(key);
if (saved) {
return JSON.parse(saved);
} else {
return null;
}
}
your object:
var lsTest = {
id3333: {
postUrl: postUrl1,
postTitle: postTitle1,
postThumb: postThumb1,
},
id4444: {
postUrl: postUrl2,
postTitle: postTitle2,
postThumb: postThumb2,
}
}
store it:
saveObject('myUniqueSiteName', lsTest);
retrieve it:
var lsTest = getSavedObject('myUniqueSiteName');
adding a new post:
var lsTest = getSavedObject('myUniqueSiteName');
var postId = 'id555';
lsTest[postId] = {
postUrl: postUrl3,
postTitle: postTitle3,
postThumb: postThumb3,
}
saveObject('myUniqueSiteName', lsTest);
Variable variables are not a good idea even in PHP. Just make an array or a hash (which is an object, but it's used as a hash or map, where you can add and delete properties or entries as you please).
var posts = {};
var someId = 3333; //or '3333' if it isn't a number
posts[someId] = {
URL: postURL,
title: postTitle,
thumb: postThumb
};
localStorage.setItem('post' + someId, JSON.stringify(posts[someId]));
A property named "foo" on an object named "bar" can be accessed like so:
bar.foo = 'baz';
console.log(bar.foo);
or like so:
bar['foo'] = 'baz';
console.log(bar['foo']);
Which is the same as:
var name = 'foo';
bar[name] = 'baz';
console.log(bar[name]);
Finally, the global object in JavaScript (which in the browser is window) "holds" the global variables.
var myGlobal = 10;
console.log(window.myGlobal); // logs 10
var globalName = 'foo';
window[globalName] = 'baz';
console.log(foo); //logs 'baz'
Using global variables in general is discouraged. Using them to store posts where the name of the var is the id is highly unorthodox and many JS developers would consider it simply wrong.
I have the following property defined for my database access in nodejs. The problem is that I need also the url parameter defined for a certain function. I have therefore written the helper function getDataUrl()
var config = {
db: {
db: 'dbname', // the name of the database
host: "12.12.12.12", // the ip adress of the database
port: 10091, // the port of the mongo db
username: "name", //the username if not needed use undefined
password: "pw", // the password for the db access
url: undefined // also tried url: getDataUrl()
}
};
function getDataUrl() {
var dataUrl = "mongodb://";
if (config.db.username !== undefined) {
dataUrl += config.db.username + ':' + config.db.password + '#';
}
dataUrl += config.db.host + ":" + config.db.port;
dataUrl += '/' + config.db.db
return dataUrl;
}
module.exports = config;
However I do not want to call this function but use instead the property config.db.url.
I am at the moment struggling how to do that. I have tried the following:
write url: getDataUrl() this produce: TypeError: Cannot read property 'db' of undefined
call getDataUrl() which then writes the property, however this does not overwrite the url property. When I then read the value the following error occures: Cannot read property 'url' of undefined
write config.db.url = getDataUrl(); this also does not overwrite the url property.
I am very new to JavaScript and nodejs therefore I do not know how to achieve this behavior or if it is even possible.
You could try a getter property:
var config = {
db: {
db: 'dbname', // the name of the database
host: "12.12.12.12", // the ip adress of the database
port: 10091, // the port of the mongo db
username: "name", //the username if not needed use undefined
password: "pw", // the password for the db access
get url() {
var dataUrl = "mongodb://";
if (this.username)
dataUrl += this.username + ':' + this.password + '#';
dataUrl += this.host + ":" + this.port + '/' + this.db;
return dataUrl;
}
}
};
console.log(config.db.url); // automatically computed on [every!] access
To fix
write url: getDataUrl() this produce: TypeError: Cannot read property
'db' of undefined
you should change the "configs" variable to "config" in your getDataUrl() function:
function getDataUrl() {
var dataUrl = "mongodb://";
if (config.db.username !== undefined) {
dataUrl += config.db.username + ':' + config.db.password + '#';
}
dataUrl += config.db.host + ":" + config.db.port;
dataUrl += '/' + config.db.db
return dataUrl;
}