Managing Elements

How to respond to new Elements and display them

Within an Event, creators or automations will be publishing Elements – bi-directional content units that have certain properties and behaviours built in, as defined in the App Spec. In general, there are two types of Elements:

  1. Interactive Elements: those that are bi-directional in nature and allow your users to interact with the content. For example by providing live results and seeing how other people have responded. You might choose to define an interactive Element to behave like a poll, containing a question, a number of possible answer options and a duration.

  2. One-way Elements: those that are broadcast to all, but do not require a response. For example an information unit, like a message, promotion or image gallery.

An Event may include multiple Elements. For example if you create an Event for a soccer game, an Element might be a result prediction appearing before the game starts and another that triggers whenever a goal is scored.

Interaction is the purpose of the platform, but we'll start with simpler one-way Elements.

One-way Elements

Let's look at how to use non-interactive One-way Elements in your application.

The snippet below retrieves the array of Elements already existing within the Event and illustrates how you can use its contentType to differentiate each Element type. In the example, we determine a single type of Element being received - goalScored.

async function displayElements(event) {
  try {
    const elements = await getElements(event);

    for (const element of elements) {
      switch (element.contentType) {
        case 'goalScored':
          displayGoalScored(element);
          break;
      }
    }
  } catch (e) {
    console.error('Something went wrong!', e);
  }
}

function displayGoalScored(element) {
  // In this function we know the element is a goal scored, so we can 
  // equally make some assumptions about what data will be available.
  // As you can see below, given the control you have over the App 
  // Spec, you can provide via Studio as much data as you want to support,
  // in this example the goal scorer name, number, and the amount of goals
  // they scored today, so you can add some extra fanfare
  // in your UI when they score a hat trick!
  const {
    fields: {
      goalScorerName,
      goalScorerNumber,
      goalScorerGoalsToday,
    },
  } = element
  
  // Draw the UI based on your UI framework.
}

getElements will return a list of elements sorted so that the most recent element is first, and the oldest is last.

Additionally, you can subscribe to updates to a given Element using the following snippet:

// Called when the results of an interactive element change
const unsubscribeOnElementResults = onElementResults(
    element, 
    (results) => { console.log(results) }
);

// Called when the element is updated
const unsubscribeOnElementUpdated = onElementUpdated(
    element, 
    () => { console.log(element) }
);

// Called when the state of the element is updated
const unsubscribeOnElementStateChanged = onElementStateChanged(
    element, 
    () => { console.log(element) }
);

Interactive Elements

Interactive Elements get fans involved and make your experiences more rewarding. They have the following properties which differ from One-way Elements:

  • State: open or closed state, where open means the user can still interact with the Element. The timespan where the user can vote can be obtained through the duration property.

  • Question and AnswerOptions: The Element usually will have a question associated with it for the user to answer by interacting with some potential answers. Through the App Spec you can specify what data is included in either the Question and AnswerOptions. This enables you to create rich questions and answers which could include videos, images, links to other content on your application, ...

  • Results: Results bring a sense of belonging into your users interaction, by letting your users know how their peers are answering a question. You will receive these values both as a total vote count as well as a percentage of the total votes.

The snippet below updates the previous one to add a new type of element, a poll:

async function displayElements(event) {
  try {
    const elements = await getElements(event);

    for (const element of elements) {
      switch (element.contentType) {
        case 'poll':
          displayPoll(element);
          break;
        case 'goalScored':
          displayGoalScored(element);
          break;
      }
    }
  } catch (e) {
    console.error('Something went wrong!', e);
  }
}

function displayPoll(element) {
  const {
    question: {
      text: questionText,
      imageURL: questionImageURL,
    },
    answerOptions,
    state,
    fields: {
      poll_custom_field: pollCustomField,
    }
  } = element;
  
  const answers = answerOptions.map(({ text }) => text);
  
  // Draw the poll
}

Responding to an Interactive Element

Once you have displayed the answer options on screen, submit the user's answer using the answer()method.

In the snippet below we show how an answer can be submitted, alongside its error handling so you can contextualise to the user if anything goes wrong. We assume that the variable userAnswer contains the 0-based index of the answer option selected by the user.

function sendAnswer(element, index) {
  try {
    // index should be e.g. 0 to the count of options available - 1
    answer(element, index);
    // Your answer was sent successfully
  } catch {
    if (e instanceof MonterosaError) {
      switch (e.code) {
        case AnswerError.OptionIndexOutOfRange:
          // The index is outside the range of possible options
          break;
        case AnswerError.AboveMaxVoteOptions:
          // You voted for more indexes than is allowed
          break;
        case AnswerError.BelowMinVoteOptions:
          // You voted for fewer indexes than is allowed
          break;
        case AnswerError.AboveMaxVotesPerUser:
          // You voted with a higher total value than is allowed
          break;
        case AnswerError.AboveMaxVotesPerOption:
          // You voted with a higher value than is allowed in a single option
          break;
        case AnswerError.VotedOnNonInteractiveElement:
          // You tried to vote on a non interactive element
          break;
        case AnswerError.VotedOnClosedElement:
          // You voted on closed element
          break;
        default:
          // Shouldn't occur, but be ready for it as more cases could be added in the future.
          break;
      }
    } else {
      // Shouldn't occur
    }
  }
}

Elements can be configured to allow for multiple answers through their App Spec using three values:

  • Maximum votes per user: This specifies how many votes a user can cast, either on the same option or on multiple options. E.g. a user can emit 5 votes for a given question, either all 5 on the same option, or spread through multiple options.

  • Maximum and Minimum options per vote: This specifies the minimum and maximum options a user must include in their vote. E.g. a user must pick at least 2 options and at most 3.

In some scenarios, you may wish to validate that a given answer is correct before attempting to submit it. For instance, this could be helpful if you want to highlight in red that the user's choice is not a valid response and accompany with some explanatory text on how to correct it.

To that effect, we offer you a method called validateAnswer() that lets you perform the same validations the answer() method performs, and reports any potential errors in the same manner.

// You can validate your answer at any point, so as to provide
// feedback to your user about what went wrong:
try {
  validateAnswer(element, index);
} catch (e) {
  // The same error handling as was done when calling `answer`
}

Displaying the results of an Interactive Element

After the user selects their response to the Element, you may want to show them what other people are saying. The platform collects responses and periodically sends aggregated stats back to all connected clients. Here's how you receive those results:

function displayPoll(element) {
  // ...
  const { results } = element;

  if (results === null) {
    // We don't have yet results, so reflect the case on the UI
    return;
  }

  // We are able to show results to the user
  const voteCount = results.map((result) => result.votes);
  const votePercentage = results.map((result) => result.percentage);
}

Revealing the correct option or result

You can also display to the user which of all the options is the correct option to select, which is a critical feature when building for instance a Quiz.

The following snippet showcases how we check if the user has already submitted an answer, and if so, we obtain the correct option. Notice that depending on how you configure your Element in the App Spec, the correct option may be revealed at different times, so it's possible that the user has answered, but the real answer is not yet received. This is common when building Prediction Elements.

if (element.userAnswer === null) {
  return;
}

const correctOptionIndex = element.correctOption;
// Highlight the correct option from your collection of options

Last updated