Pergunta

Basically in my website I have a sidebar with a stack of boxes; each box can be collapsed or expanded by the user. I need to save the status of each box for the currently logged in user. I don't want to use cookies because if an user changes browser or computer, all the boxes will go to the default status.

Should I save this information on the database making a query every time the user collapses/expands a box? How would you handle this? Thanks.

Edit: What if an user clicks on the toggle button repeatedly, like ten times in two seconds, just because he enjoys the boxes' animation? He will make ten queries in two seconds. So maybe the question should be: when should I save this data?

Foi útil?

Solução

  1. Call a (client-side) "changed" function every time a box changes.

  2. Keep two items of (client-side) state: the time the last update to the server was sent and whether a timer has been set.

  3. Write a (client-side) "update" function that sends the update and updates the state to mark that the last update was just now.

  4. When the changed function is called: if a timer is set, then return immediately; if an update has never been sent or the last update was sent more than ten seconds ago, then call the update function and return. Otherwise set a timer to send the update after ten seconds.

  5. The timer callback should simply clear the timer flag and call the update function.

  6. Also on an unload event check if a timer was set and if it was then clear the timer and call the timer callback function.

So the result is that you send the update immediately except when the user is flapping, in which case you only send an update every ten seconds at most.

There might be some cases where you lose an update, but this is likely to only happen if the user was playing with the toggling and then closed the page before the timer fired, in which case he probably won't notice anyway.

Outras dicas

If you need to persist these options from multiple computers you will need some form of server side storage.

This could be database or flat file. The choice depends on what you have available, skill set, and the need to scale. If you are going to have just a few users, a flat file may be your best choice.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top