Elements

Elements are the powerful building blocks of an LViS app. They include the logic and back-end aggregation that handles quizzes, polls and other types of two-way data exchanges.

Lets imagine that your App uses the Quiz to show questions to users. Lets see how we can receive element and watch for when that element changes.

// assume LViS Event exists and is set as active
var event = LViS.getEvent();
var quiz;
var handleState = function (state) {
// Do something when you receive a new Element
};
// Triggered when a new Element is triggered
event.on(LViS.Event.ON_ELEMENT_PUBLISH, function (element) {
switch (element.getContentType()) {
case LViS.Quiz.TYPE:
quiz = element;
// Listen to the quiz Element's state change
quiz.bind(LViS.Quiz.ON_STATE_CHANGE, handleState);
// Force handling of the quiz's current state
handleState(quiz.getState());
break;
}
});

With this in place we now have a handy way of triggeriong the UI to show questions starting, closing and ending.

Finally lets look at what to do with the Quiz element, how to get the question and answer options and then how to reveal the correct answer.

Firstly lets modify the handleState to call a function that handles rendering, for various Quiz states

var handleState = function (state) {
switch (state) {
case LViS.Quiz.STATE_STARTED:
// Show options
renderQuiz();
break;
case LViS.Quiz.STATE_STOPPED:
// Stop collecting answers and disable controls
stopQuiz();
break;
case LViS.Quiz.STATE_REVEALED:
// Show results
revealQuiz();
break;
}
};
var renderQuiz = function () {};
var stopQuiz = function () {};
var revealQuiz = function () {};

Now lets take each of those render functions in turn. First lets look at rendering the question. We can quickly get everything we need to display that question.

var renderQuiz = function () {
var question = quiz.getQuestion();
var options = quiz.getOptions();
var remaining = quiz.getDurationLeft();
// Then use those variables to update your UI, i.e:
// * display Question Text;
// * create buttons for each answer options
// * make sure buttons call quiz.vote();
// * add countdown
};

When the Quiz Element ends, you might want to then disable the buttons to stop accepting button presses.

var stopQuiz = function () {
// Disable any option buttons
// Change state of countdown
};

It's when the answer is revealed that you'll usually do something significant, like figuring out if the user got the question right. LViS has convenience methods to help with this.

var revealQuiz = function () {
if (quiz.hasUserVoted()) {
if (quiz.getCorrectOption() === quiz.getUserVote()) {
// User was correct
} else {
// User was wrong
}
} else {
// User didn't vote
}
// Update UI accordingly
};