Listening for flag changes

Modern web, mobile, and desktop applications are sometimes used for long sessions at a time. For example, web applications built as a single-page app like Gmail and Google Calendar are typically left open in a browser tab for long periods. New features may not be available to a user until the next time the tab is reloaded.

Using LaunchDarkly's client-side SDKs, you can release features to your users without requiring them to reload the game. Your applications can respond to feature flag changes more rapidly since your app is listening for flag changes all the time, not just at the time the page is reloaded.

Earlier in this lesson, you added an event listener for the ready event so the app knew which sprite sheet to load before the game started. But ready isn't the only event emitted by ldclient. We can listen for change and change:<flag key> events in order to listen for changes to all flags, or specific flags, respectively.

To add an event listener:

  1. Add the following code to the bottom of js/app.js:
    ldclient.on('change:space-mode', function (currentValue, previousValue) {
       if (currentValue == true) {
          // switch to Space Mode
          smallSprites.src = "/images/100-percent/100-sprite-space.png";
          largeSprites.src = "/images/200-percent/200-sprite-space.png";
          // Change the game name heading
          heading.innerText = "Toggle Runner";
       }
       else {
          // switch to Dinosaur Mode
          smallSprites.src = "/images/100-percent/100-sprite.png";
          largeSprites.src = "/images/200-percent/200-sprite.png";
          // Change the game name heading
          heading.innerText = "T-Rex Runner";
       }
       // Both changes require the game to update
       Runner.instance_.updateGraphics();
    });
    
    You do not need to call variation() here because the change:<flag-key> events pass the current and previous values of the flag as arguments to the event handler.
  2. In Replit, click the Run button to reload the game.
  3. Toggle the space-mode flag on from the LaunchDarkly dashboard.
  4. In Replit, the header and graphics change without refreshing your browser.