It’s how I think XBlock JavaScript should be done going forward, but as far as I know, nobody has yet done it that way. So it would require some innovation and exploration. I’ve been hoping to prepare a demo of that (or convert an existing XBlock to do that) one of these days, but it’s unfortunately been on the back burner for a while.
That said, Ramshackle is a Studio plugin that I created, and it uses TypeScript to do that (transpile the source code and bundle in all the requirements like React, producing a single .js
file; it’s done with the make js-watch
command). So I’d likely use a very similar approach for an XBlock.
Using window.onload
in that manner is not dependable, because the XBlock is often (always?) loaded “lazily”, after the window.onload
event has already fired.
Instead, your JavaScript code should contain some main function like:
function MyBlock(runtime, element, configuration) {
console.log("Some functionality");
}
and then in the python student_view
, you tell the runtime to run that function when the block loads, like this:
configuration = {} # Optional data to pass from python to JavaScript
fragment.initialize_js('MyBlock', configuration)
return fragment
Check the source code of almost any XBlock for an example.