chrome.storage.sync.set not saving values - javascript

So I've run into a bit of snag with regards to local storage on Google Chrome. From what I've researched, my syntax seems to be correct, but for some reason the value is not being saved. Here's my code:
chrome.storage.sync.get(accName, function(data) {
var accData = data[accName];
// Stuff
chrome.storage.sync.set({ accName: accData }, function() {
alert('Data saved');
});
});
Every time I re-run it, data[accName] returns undefined. I've tried the same code with literal values for the sync.set parameters (eg. { 'john32': ['fk35kd'] }), and that seems to work, so I'm really confused as to what the issue could be. Any help would be appreciated.

The issue was trying to plug accName into an object literal inside the set statement (credit to Rob above). What I'd end up with was an object with a property 'accName' rather than the value of accName itself. Here's a fix.
var obj = {};
obj[accName] = accData;
chrome.storage.sync.set(obj, function() {
alert('Data saved');
});
Update
ES6 now allows computed property names in object literals, so the above can be achieved with:
chrome.storage.sync.set({ [accName]: accData }, function() {
alert('Data saved');
});

Related

Setting JSON node name to variable value

I've spent most of my time in languages like Java and C++ but I'm trying to pick up JavaScript. What I'm attempting to accomplish is a way to set the parent node name by the value of the variable passed. I am using Firebase if that makes a difference in this code but I didn't think it would.
var parent_node_name = "EPLU200";
var onComplete = function(error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
}
};
// update adds the data without replacing all of the other nodes
myFirebaseRef.update({
parent_node_name: { // trying to change this part to not save as "parent_node_name"
id2: "1175", // but instead as "EPLU200"
...
}
}, onComplete);
The action saves to my Firebase server just fine but the problem is passing the actual value of the variable instead of reading the variable name.
Is there any workaround in JavaScript? I tried searching for it but I didn't know what to call it.
Depending on the environment (i.e node?)
myFirebaseRef.update({
[parent_node_name]: {
id2: "1175",
...
}
}, onComplete);
See the code commented as Computed property names (ES6) in New Notations in ES2015 doumentation at MDN
if that doesn't work, you have to do this
var obj = {};
obj[parent_node_name] = {
id2: "1175",
...
};
myFirebaseRef.update(obj, onComplete);

Multiy String Variable Names Not Working In Javascript

Recently I posted about Dynamic Names in Javascript. I went ahead and tried to make a multi string variable name (combining a string and a variable to make a new variable name), and it does not seem to work. I am very confused because I am doing what many posts on SO say to do (so I think anyhow).
Anyhow here is the dynamic variable I am using:
var dynamic["replyupvote"+replyid] = false;
and then when I am calling it I use:
dynamic["replyupvote"+replyid]
So my question is where am I going wrong? If you would like to see my full code:
function replyupvote(replyid, upvotes, downvotes, votesclass, votesnumber) {
var dynamic["replyupvote"+replyid] = false;
return function() {
if (dynamic["replyupvote"+replyid]) {
dynamic["replyupvote"+replyid] = true;
}
else {
$.ajax({
url: "http://localhost/postin'/categories/votes.php",
type: "POST",
data: { 'itemid': replyid,
'userid': <?php echo $_SESSION["logged_in"]; ?>,
'action': "upvotes",
'type': "reply" },
success: function() {
$("." + votesclass).css("color", "orange");
$("." + votesnumber).text(parseInt(upvotes - downvotes) + 1);
}
});
dynamic["replyupvote"+replyid] = true;
}
}
}
This code worked before I through in the Multi String Variable Names. So what am I doing wrong? Thank You! :)
EDIT
I thought I should throw this in. Javascript throws the error that the function is not defined because of the incorrect syntax.
Regardless if what you are doing here makes sense or not, to dynamically create properties on an object, you will need to make sure JS knows it's an object, not an array. So before you try to create a dynamic object property, explicitly declare dynamic as an object:
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
That should get rid of the syntax error at least.
You would have to set dynamic as an object first
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
variableName[keyName] = value; is the syntax of an object.
You have to tell js that your variable is an object before you can use this notation.

Meteor.js Collection empty on Client

Why is it that myCollection.find().fetch() returns an empty array [] even though the call is made within if(data){...}? Doesn't the if statement ensure that the collection has been retrieved before executing the console.log()?
Template.chart.rendered = function() {
var data = myCollection.find().fetch();
if(data) {
console.log(data);
}
$('#chart').render();
}
This returns [] in the browser Javascript console.
You could use count() instead which returns the number of results. data itself would be an empty array, [] which isn't falsey ( [] == true ).
Also don't use fetch() unless you're going to use the raw data for it because its quite taxing. You can loop through it with .forEach if you need to.
var data = myCollection.find();
if(data.count())
console.log(data);
//If you need it for something/Not sure if this is right but just an example
$('#chart').render(data.fetch())
The problem is that you have to wait for data from the server. When you just use Template.name.rendered function it is immediately invoked. You have to use Template.name.helpers function to wait for data from the server. Everything is described in the documentation.
It seems when you "remove autopublish" you have to also subscribe on the client.
if(Meteor.isClient) {
Meteor.startup(function() {
Myvars = new Mongo.Collection("myvars");
Meteor.subscribe('myvars')
});
}
and enable allow and publish on the server
if(Meteor.isServer) {
Meteor.startup(function () {
Myvars = new Mongo.Collection("myvars");
Myvars.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
if (Myvars.find().count() == 0) {
Myvars.insert({myvalue:'annoyed'});
}
Meteor.publish("myvars", function() {
return Myvars.find();
});
});
}
I'm new to this as well. I was just looking to have a global value that all clients could share. Seems like a useful idea (from a beginner's perspective) and a complete oversight on the Meteor teams behalf, it was nowhere clearly documented in this way. I also still have no idea what allow fetch is, that too is completely unclear in the official documentation.
It does, but in javascript you have the following strange behaviour
if ([]){
console.log('Oops it goes inside the if')
} // and it will output this, nontheless it is counter-intuitive
This happens because JS engine casts Boolean([]) to true. You can how different types are casted to Boolean here.
Check if your array is not empty in the beginning.
a = [];
if (a.length){
//do your thing
}

On object parameter is not properly set in JavaScript

I have the following code in my website:
function GroupObject(GroupID, GroupColor, GroupName, CalendarID, UserEnable, IrcChannel) {
this.uid = GroupID;
this.color = GroupColor;
this.groupname = GroupName;
this.calendarid = CalendarID;
this.userenable = UserEnable;
this.ircchannel = IrcChannel;
}
function GetGroupObjects(callback) {
var GlobalDB = [];
$.getJSON("Some Data From Google Docs",
function (data) {
$.each(data.feed.entry, function (i, entry) {
GlobalDB.push(new GroupObject(entry.gsx$uid.$t,
"000000",
SanitizeInputText(entry.gsx$group.$t),
SanitizeInputCalID(entry.gsx$calendarid.$t),
true,
SanitizeInputText(entry.gsx$ircchannel.$t)))
});
console.log(GlobalDB[0]);
console.log(GlobalDB[0].color);
callback(GlobalDB);
});
};
All the parameters of the newly created GlobalDB are correct with the only exception of the parameter "color". console.log(GlobalDB[0]) returns:
GroupObject
calendarid: "CalOfTNG"
color: "AB8B00"
groupname: "Austin TNG"
ircchannel: "AustinTNG"
uid: "TNG"
userenable: true
__proto__: GroupObject
It brings the same value for color "AB8B00" in both Chrome and Firefox. Any idea why? From the code above it should be 0. console.log(GlobalDB[0].color) does returns 000000. But when
I use GlobalDB when returning from the callback I get again AB8B00.
user enable, on the other hand works just fine. I just cannot find what is causignt he problem with the parameter .color as it fails in both Chrome and Firefox.
Thanks in advance.
You seem to be subject to a console.log problem I have experienced often: you don't see the object exactly as it is when logged but as it is later, because the browser doesn't deep clone it immediately when you log but just stores its reference.
This effect doesn't affect primitive, like strings, that's why the color appears initially fine when you log GlobalDB[0].color.
The color is "000000" when you log it. It changes after, probably when you call callback(GlobalDB).
See also this related question (and answer).

Store jquery function on variable

I have this code in .js file:
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
if (data.address.country='spain') {
var a="http://www.link1.com";
} else {
var a="http://www.link2.com";
}
return a;
});
var fan_page_url = data();
How can I store var a in var fan_page_url ?
Thank you very much.
Try getting rid of a and assigning the links directly.
var fan_page_url;
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
if (data.address.country = 'spain') {
fan_page_url = "http://www.link1.com";
} else {
fan_page_url = "http://www.link2.com";
}
});
You have two options: assigning the external variable directly, as depot suggested, or treating the $.getJSON return value as a Deferred:
$.when($.getJSON(...)).done(function(returnValue) {
fan_page_url = returnValue;
});
The latter is useful in case you don't want to hardcode the variable you'll store the results (though in general it's not a problem, and the former option is easier/cleaner).
It's an old question on which I just stumbled (looking for something slightly different) but as answers did not seem to hit the nail on the head, I thought I'd add 2 cents: if you (op) had success with a variable that was hardcoded and set manually in config.js, that you were able to grab from start.js, why not simply:
keep the variable declared like you did in the global scope
assign it a default or null or empty value:
var fan_page_url = null; // or
var fan_page_url = ''; // or
var fan_page_url = 'http://url_default'; // etc...
then update the global variable inside the json function:
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
if (data.address.country='spain') {
fan_page_url = "http://url1";
} else {
fan_page_url = "http://url2";
}
});
in your start.js page, you can always perform a check to see if the variable is set or not, or still carries it's default value or not and act accordingly...
It is likely that if it used to work with your normally, manually declared variable, it would work the same here as you would have changed nothing structurally, only would be updating the variable after the json response.
Answer posted for the posterity, it may help someone in the future.

Categories

Resources