For a number of different reasons, I am making my current game using a javascript framework called Meteor JS. In the course of doing so, I also have to learn this framework and some of its intricacies.
Quick Summary of Methods
Meteor uses MongoDB as the default database. To simulate your app running faster, it keeps a copy of the database in the browser along with the copy on the server.
For some actions such as logging in, we don’t want to allow users to do database modifications from the client side. This is a security risk.
Thankfully, Meteor has server side code that can be called from the browser using its Meteor Methods interface.
The Problem
Like any good game, I am trying to have a little bit of graphical display that currently consists of a simple canvas that draws colored squares that represent the players and their opponent’s units.
Because drawing over and over would be processor intensive, we only want to draw the canvas when it changes. Initially when we load the page, we get the positions of the units and draw them on the map.
However when we move, we are sending asynchronous calls to the database. This presents a race condition. The page could load before the server database is synced with the browser database resulting in an non updated canvas when it is drawn.
The Solution
The creator of Meteor must have stumbled across this before because there is a nifty little wrapper to put around your code if you want it to run when the database is updated.
It is Tracker.autorun()
and allows you to maintain security by running code solely on the server while still tracking the changes in the database and allowing your app to be reactive.