In a Google spreadsheet using the Script Editor, I do function calls, but I am not quite sure if the best way to store persistant data (data that I will continue to use) is to use global variables (using objects, arrays, strings), or there is a better way to store data.
I don't want to use cells which could be another way.
Another question, is it possible to create (pseudo) classes in this environment? Best way?
Both ScriptProperties and ScriptDB are deprecated.
Instead, you should be using the new class PropertiesService which is split into three sections of narrowing scope:
Document - Gets a property store that all users can access within the current document, if the script is published as an add-on.
Script - Gets a property store that all users can access, but only within this script.
User - Gets a property store that only the current user can access, and only within this script.
Here's an example persisting a user property across calls:
var properties = PropertiesService.getScriptProperties();
function saveValue(lastDate) {
properties.setProperty('lastCalled', lastDate);
}
function getValue() {
return properties.getProperty('lastCalled');
}
The script execution environment is stateless, so you cannot access local variables from previous runs, but you can store getScriptProperties() in a local variable because it will be re-run for each return trip to the server so it can be called in either method.
If you need to store something on a more temporary basis, you can use the CacheService API
Persistent data can be stored using the Class ScriptProperties:
http://code.google.com/googleapps/appsscript/class_scriptproperties.html
All values are stored as a string and will have to be converted back with the likes or parsInt or parseFloat when they are retrieved.
JSON objects can also be stored in this manner.
My experience has been that every query to retrieve or store values takes a long time. At the very least, I would cache the information in your javascript code as much as possible when it is safe. My scripts always execute all at once, so I don't need to keep global variables as I simply pass the retrieved data arrays around, manipulate them, and finally store them back in one fell swoop. If I needed persistence across script invocations and I didn't care about dropping intermediate values on close of the webpage, then I'd use globals. Clearly you have to think about what happens if your script is stopped in the middle and you haven't yet stored the values back to Google.
Related
A have a react application using a single page. I call index.html and use ajax(axio) and update the page. I do not use any routing.
I have some global variables and will use in the whole scope of the application. The variables are primitive type integer for example. Some of the variables may be updated during the app lifecycle and some remain constant. But I should be able to reach them from all react components/javascripts. They may contain business related constants or example decimal format mask, keeping them private in each component will not be useful.
There is no need/reason to store it on the disk (localStorage).
Question is: what is the best way (performance etc) storing the global variable foo in the app?
window.foo = 10 or
window.sessionStorage.foo = 10
AFAIK, window.foo is for a single page and sessionStorage allows using within multiple pages within the same origin. What is best in my case when I use a single page? Are there any other drawbacks of window.foo usage? Security is not important, the vales stored are not sensitive. Most critical is the performance.
You probably want to use context rather than either of those. From that documentation:
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Definitely don't use global variables. The global namespace is incredibly crowded, and adding to it is generally not best practice. If you did use a global for this, I'd recommend using just one, and having it refer to an object with properties for the various pieces of information you want to share. Note that they'll be window-specific.
One reason to possibly consider using sessionStorage (or perhaps periodically synchronizing your React context to it) is if you want changes in one window to be reflected in another window. Two windows/tabs from the same origin share the same sessionStorage and can get an event (storage) when the other one changes that storage. So if the global information were an app theme (say, light vs. dark), changing it in one tab could also affect the other tab if you respond to the storage event by updating your React context. Note that sessionStorage (and localStorage) only store strings, so the usual thing is to convert to JSON when storing (JSON.stringify) and from JSON when loading (JSON.parse).
I have a long javascript function (about 72k minified) that is required on several pages of my site. My existing method to employ the function on my pages is to call the script by the usual means:
<script type="text/javascript" src="./javascript/complex_function.js"></script>
However, this involves reading and parsing the script on each page on which it is required. If I could store the function in my browser's memory and simply call it from there, then it would seem more efficient and faster (yes?)
Sadly, it seems that sessionStorage only supports the storages of keys and values that are strings. I've tried stringifying the function (as discussed elsewhere re: Javascript objects being stored in sessionStorage or localStorage), like so:
// First call the function in an initial page of the site:
<script type="text/javascript" src="./javascript/complex_function.js"></script>
// Then stringify it and store in sessionStorage:
sessionStorage.setItem('my_function', JSON.stringify(my_function));
Thereafter, in theory, I should be able to retrieve the function from sessionStorage anywhere session is active on my site, like this:
var temp = JSON.parse(sessionStorage.getItem('my_function');
...although (1) this doesn't work, or at least I can't find a way to make it work, and (2) even if I could make it work, it would still involve parsing the function, which would defeat the purpose (right?)
So...what is the best way to store a Javascript function in memory (no cookies, please) so that it can be called from any page on my site? (Or is this possible at all?)
Your browser will already do this for you. It will cache scripts upon their first download to reduce loading times, so once it's loaded the first time successive requests for that file will be quicker as it is pulled from the local machine, not the server.
first of all, I don't think it's a good idea to store js functions in memory.
And per my experiences, the sessionStorage only store string values, so you can try eval()
I'm building an app which needs to know where the user is; it displays events within a radius of the user.
I'm using the Google geocoding API and have been saving the returned object as a session variable and passing the info to and fro using ajax to retrieve and update the location.
I've noticed that occasionally the array and object keys will be different. For instance, sometimes it will have a nicely formatted results.geometry.location.lat hierarchy, but then occasionally it will be results.geometry.location.d and sometimes even results.geometry.location.A.
I created a getter in javascript which will return the lat and lng regardless of the keys returned. I'm surprised that the returned objects don't have built in getter functions when the array keys vary like that.
So, I'm wondering if there's a better way to store the user's location than just saving the entire geolocation response. I tried paring it down to just what I want to use, but that means every time I make a call to Google for a location, I need to process it.
Has anyone had any experience getting this sort of thing to work?
Thanks
EDIT:
I'm using cakePHP and I realized I should have made this a datasource from the get-go. I currently have all the logic in a component being called from my controllers. I'm going to spend some time creating a datasource, which should take care of the getting and setting of this mutating object.
I have a web app, which has 2 html pages(html1,html2 related to javascript file js1.js,js2.js)
When I click a button on html1, it will navigate to html2.
I know there is the way transfer the parameter using url from html1/js1/js to html2/js2.js.
Is there a mechanism that set up variables both j1.js j2.js can access?(likes global variable in c)
Welcome any comment?
This is not directly possible as each page loads with its own window object namespace.
i.e. A global variable in js1.js (used in page1.html) is actually a member of the window object in page1. Similarly a global variable in page2.html is a member of that page's window object. The 2 window objects are totally different in the sense there is no site wide window or site object that can store global variable for use throughout a site
You can however use window.localStorage to share variables/values across pages in your site.
Example:
Setting value:
window.localStorage.setItem('myglobal', "hello");
Getting value:
var myglobal = window.localStorage.getItem('myglobal');
A hackish solution is to store it into the window.name field. This is shared in the same window/tab of the browser.
I personally don't like it. That variable isn't meant to be used this way.
There are libraries to persist state: http://pablotron.org/?cid=1557
Or, you could write your own code to store the variable in session (requires server-side programming), in HTML5 storage, in cookies, etc.
Variables and values can be passed through pages via querystring.
Have a look at this SO article.
If you strictly need to create a Javascript global variable, then you have to include a common snippet in both pages:
var myGlobalVar;
But this only represent a storage accessible by both scripts. You have to set its value anyway.
You can either parse window.location.href to extract the parameters, set cookies in one page and retrieve them in the other (example here) which also requires parsing or use a server-side solution.
Most probably if you look for in interwebs you can find parsers for URLs and Cookies.
I am using the new(ish) chrome.storage.sync API for a chrome extension and the when saving objects, it completely ignores functions.
This means that when I retrieve objects from storage, I have the data in the object, but no functions.
Is there a way to reconnect the object's data to its functions?
Note: I'm not doing anything weird in the functions (like adding variables to it or changing its closure)
You basically need to run your object through a constructor function after it comes out the data storage thing.
I don't think there is a way to save functions persistently.
You could save an object with like.. self.fns=['fn1','fn2']; and on reload, add the functions back based on that.
But you should probably change your design if you are dynamically adding functions to things and need to save them that way.