Share Application State

This example uses Orbiter, JavaScript, and HTML to share application state among all users in a connected application. In Union applications, users are grouped together in rooms. Rooms supply a context for a connected activity, such as subscribing to a data feed, competing in a game, or pushing application data to members of the group. For example, in a live quiz, users might join a single, massive game room that broadcasts the quiz's questions to players. Or in a meeting application, users might join a variety of individual rooms, one for each separate meeting being held.

To share application state among the users in a room (aka, the room's "occupants"), Union applications use room "attributes". In a quiz application, the shared application state might be the text of the current question. In a chess application, the shared application state might be the location of pieces on the chess board.

The code in this sample shows how to set two room attributes to be automatically shared with all room occupants. The first room attribute is lastOccupantJoinedAt, which is a timestamp indicating when the most recent room occupant joined the room. The second room attribute is numOccupantsLifetime, which is a running tally of the number of users that have ever joined the room. To maintain numOccupantsLifetime, the code uses setAttribute() method's "evaluate" argument, which updates the attribute using a simple math operation on the current server-side value.

Here's the shared-state application:

[Edit Live on JSFiddle] [Download]

This application demonstrates the following Orbiter features:

  • Creating a room that exists until Union Server shuts down
  • Joining a room
  • Sharing a room attribute
  • Incrementing a room attribute with client-side code
  • Responding to room attribute updates

The Code

Here is the code for the preceding example. Click the "+" button to edit it live on JSFiddle.