This section of the tutorial walks through the JavaScript file, thumbs.js, that is part of the Thumbs XBlock in the XBlock SDK.
If you completed the steps in Build an XBlock: Quick Start, you can find
this file locally at xblock_development/xblock-sdk/sample_xblocks/thumbs/static/js/source/thumbs.js.
In the XBlock JavaScript file, you define code that manages user interaction with the XBlock. The code is added to a fragment.
The XBlock’s JavaScript uses the runtime handler, and can use the children
and childMap functions as needed.
The JavaScript references the XBlock fields and methods. The fragment is returned by the view method, to be displayed by the runtime application.
function ThumbsAside(runtime, element, block_element, init_args) {
return new ThumbsBlock(runtime, element, init_args);
}
function ThumbsBlock(runtime, element, init_args) {
function updateVotes(votes) {
$('.upvote .count', element).text(votes.up);
$('.downvote .count', element).text(votes.down);
}
var handlerUrl = runtime.handlerUrl(element, 'vote');
$('.upvote', element).click(function(eventObject) {
$.ajax({
type: "POST",
url: handlerUrl,
data: JSON.stringify({voteType: 'up'}),
success: updateVotes
});
});
$('.downvote', element).click(function(eventObject) {
$.ajax({
type: "POST",
url: handlerUrl,
data: JSON.stringify({voteType: 'down'}),
success: updateVotes
});
});
return {};
};
Note the following details about the JavaScript file.
The function ThumbsBlock initializes the XBlock. A JavaScript function to
initialize the XBlock is required.
The ThumbsBlock function maps to the contstructor in the XBlock
Python file and provides access to its methods and
fields.
The ThumbsBlock function uses the runtime handler.
var handlerUrl = runtime.handlerUrl(element, 'vote');
The ThumbsBlock function includes the Post commands to increase the up
and down votes in the XBlock.
The XBlock JavaScript code can also use the children and childMap
functions as needed. For more information, see XBlock Children.