use JS inside course module info content

use JS inside course module info content

ved Johannes Burk -
Antal besvarelser: 2
Billede af Core developers Billede af Plugin developers

Is there a "correct" way of using JavaScript inside course module info content?

I developing a video activity plugin that makes use of bootstraps modal dialog to display the video. To make the video pause when the modal dialog is closed I insert inline JS code directly in the cached_cm_info content variable inside the video_get_coursemodule_info function like this:

$info->content .= html_writer::script("
    $('#$modalid').on('hide.bs.modal', function () {
        jwplayer('mod_video_player_$video->id').pause(true);
    });
");

A $PAGE->require() does not work because the video_get_coursemodule_info is only called if the course module info is not in the cache.

I would prefer to make use of an AMD module to correctly request jQuery and bootstrap as a dependency. At the moment the plugin needs jQuery and bootstrap loaded globally by the theme.

Gennemsnitsbedømmelse: -
I svar til Johannes Burk

Re: use JS inside course module info content

ved Tim Hunt -
Billede af Core developers Billede af Documentation writers Billede af Particularly helpful Moodlers Billede af Peer reviewers Billede af Plugin developers

Does it work to put the require_js code in the video_cm_info_view function? That is called when things are displayed, rather than when they are put into the cache.

Gennemsnitsbedømmelse:Useful (2)
I svar til Tim Hunt

Re: use JS inside course module info content

ved Johannes Burk -
Billede af Core developers Billede af Plugin developers

Yes, it works. Many thanks!

Inside video_cm_info_view($cm) function:

global $PAGE;
$PAGE->requires->js_amd_inline("
    require(['jquery', 'theme_bootstrapbase/bootstrap'], function($, bootstrap) {
        $('#".$cm->customdata->modalid."').on('hide.bs.modal', function () {
            jwplayer('".$cm->customdata->videoid."').pause(true);
        });
    });
 ");

This function is currently not documented at https://docs.moodle.org/dev/Activity_modules and I missed it to look a bit deeper into the php doc at https://github.com/moodle/moodle/blob/master/lib/modinfolib.php#L687.

Gennemsnitsbedømmelse:Useful (1)