Global variables in functions


(Joao Ribeiro) #1

Hi guys,
I am very embarrassed by asking so many basic questions.
It must be very simple but I can’t figure it out by myself.
I am being able to interact with javascript but I don’t know how to implement a global variable.
In script option I can’t write outside the given function, so whatever variable I create and initialise will be reset to zero (I am initialising a conter variable with zero) as it will be recreated and reinitialised with zero at any click in an assigned button. How can I create a global scope variable and initialise it once and use it in my functions?
I tried lots of things but no success so far.
Thanks again,
Joao


#2

In Hype, use the prefix window. for your variable name to make it globally accessible e.g.

window.myGlobalVariable = 0; 

You can then assign a variable a value of zero to reset it,

myGlobalVariable = 0; // resetting variable to original value

but you wouldn’t want to “recreate” it because it already exists.

Maybe, you could you share some examples of code you have tried so far. It will give us a better idea of what you are describing.


(Joao Ribeiro) #3

When I declare //var window.count = 0;// it gives me an error of unexpected token '. '. Should I just say window.count = 0; instead? Because when I do this way there is no error message but the variable does not initialise as a number.


(Joao Ribeiro) #4

Thanks!
I finally got it!

Thanks!

Forget my last question.

Cheers,

Joao


(Loves Hype) #5

You can also put variables in the hypeDocument context as that pointer is passed around in the current document function calls. Makes variables local to your document but accessible across scenes. Window breaches out into the page context but that might just be what you want. I avoid “polluting” the window scope if possible… depends on what you want to accomplish.


(Joao Ribeiro) #6

Thanks Max.
Cheers


#7

Max makes a good point. I work exclusively with widgets for iBooks Author and so don’t have to worry about other widgets in the same window. If I did, I’d follow Max’s advice.


#8

Woah… where’d your baseball cap go Max? :laughing: