This question is by necessity a bit general; it relates to the overall architecture of client side applications built with javascript and jquery:
I’m building a jquery based quiz application. For initial purposes I am trying to develop it entirely client side, with all the question and answer data stored in object literals in the js files (I’m not particular concerned right now that the data would be exposed in the source). I want to build it so that this implementation could readily be adapted into an ajax solution where the question data would be pulled from a php file or database.
I’ve written a question generation function which takes in the object literal describing the question and renders it as html and inserts it onto the page. My question is what would be the best practice for storing the users answer data and implementing the i/o as the user proceeds through the quiz. The questions would be displayed sequentially and there will be a logic which selects from a two dimensional grid of questions to determine which question would be rendered next based on whether the user answered correctly and the coordinate position on the question grid of the question they were on.
Happy to post any code I’ve already written if this would be helpful to providing an answer. Thanks.
The same principles apply.
Your entry point for the program will be some function which is attached to some event which kicks everything off. Typically this will be the page load function.
In this function you will set up the program (as you would in a C++ main), create variables (global or otherwise) representing program state etc. I’d guess you’d have some logic which selects and presents a question plus perhaps a ‘Ok’ button which the user should click once he’s happy with his user. At this point the browser is just waiting for user input, the user selects his answer and clicks ok. The logic of your program is probably store the answer in a variable somewhere and calculate the next question to display. For this you have added a function to the onclick event handler which implements this logic. You present the next question and voila you are back at the start of your loop.
I’d recommend getting the simple loop aspect working to get comfortable with javascript and the event model rather than worrying about whether global variables are bad or not. Your going to have at least one global variable in any case probably a reference to a more complex ApplicationState object.
I’m not sure if its part of your confusion but you know that instead of :
you can do