Create Global variable

Jump to solution
atia_kabir
Community Novice

Can we create a global variable called Flag? Its value will be either 0 or 1. It would be used to run a custom JS only once. 

1 Solution
James
Community Champion

 @atia_kabir  

Creating a global variable is probably not the way to accomplish whatever you want to accomplish as most variables are better when they are scoped to the function in which they execute. Luckily, for the most part Canvas does not expose any global variables, so you don't have to worry about clobbering theirs -- Flag is not one of them and most JavaScript conventions call for camelCase for variable names, so they don't start with a capital letter, so Flag is really unlikely to conflict with anything that other programs might expose as well. Still, all of your JavaScript code should probably be executed within a closure

Here is a block that creates an immediately invoked function expression that runs as soon as it is encountered but wraps the variables to score the variables.

(function(){
  use 'strict';
  // your code goes here
})();

Now the check to only run once depends on what you want to do. I'm not assuming that you it want it once per browser, but once per user. For example, agreeing to an honor code.

In a case like this, you could use the custom data endpoints of the Users API to store the results within Canvas. Then, when a page is loaded, the script would load the custom data to decide whether or not it has been done. Once it is done, you write that to the custom data. Custom Data is not preserved across page loads, so this involves an extra API call for every page load. This is where writing the cookie can speed up the process and perhaps save making the call. If you don't want to write a cookie, you can cache the results (since it's only done once). 

Depending on what you're wanting to accomplish, there may be other ways to accomplish things that don't involve custom JavaScript at all. For example, if you have control over the design and you want people to sign an honor code before beginning their course, you could have a module with that as a requirement and then have that module as a prerequisite for everything else in the course.

View solution in original post