This section describes how to modify the JavaScript file of the XBlock you
created, myxblock.js
, to provide the functionality in the Thumbs XBlock
example in the XBlock SDK.
In myxblock.js
, you will define code that manages user interaction
with the XBlock. The code is added to a fragment.
When you create a new XBlock, the default
JavaScript file is created automatically, with skeletal functionality defined.
In the xblock_development/myxblock/myxblock/static/js/source
directory, see
the file myxblock.js
.
function MyXBlock(runtime, element) {
function updateCount(result) {
$('.count', element).text(result.count);
}
var handlerUrl = runtime.handlerUrl(element, 'increment_count');
$('p', element).click(function(eventObject) {
$.ajax({
type: "POST",
url: handlerUrl,
data: JSON.stringify({"hello": "world"}),
success: updateCount
});
});
$(function ($) {
/* Here's where you'd do things on page load. */
});
}
The file contains JavaScript code to increment the count
field that was
added by default to the XBlock. Delete this code.
JavaScript code implements the browser-side functionality you need for your XBlock. The Thumbs XBlock uses clicks on the up and down vote buttons to call the handler to record votes.
Follow the guidelines below to implement JavaScript code.
Add the function MyXBlock
to initialize the XBlock.
The MyXBlock
function maps to the constructor in the XBlock
Python file and provides access to its methods and
fields.
Add the URL to the vote handler to the MyXBlock
function.
var handlerUrl = runtime.handlerUrl(element, 'vote');
Add Post
commands in the MyXBlock
function to increase the up and
down votes in the XBlock.
Note
Do not change the main function name, MyXBlock
.
After you have defined the JavaScript code, check your work against the code in
the Thumbs XBlock, in the file xblock_development/xblock-sdk/sample_xblocks/thumbs/static/js/source/thumbs.js
.
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 {};
};
If necessary, make corrections to the code in your XBlock so that it matches the code in the Thumbs XBlock.
After you complete your customizations to the JavaScript file, you continue on and customize the XBlock CSS file.