From 321c470a2356d038a6a0930779c9cd8a2b5f698c Mon Sep 17 00:00:00 2001 From: Kumi Date: Fri, 5 Jul 2024 12:02:11 +0200 Subject: [PATCH] feat: add event observer for course viewing Introduces an event observer to inject JavaScript into courses containing the exp360 activity when the course is viewed. The newly created `db/events.php` initializes event observers, while updates to `lib.php` define the event observer callback and the observer list. Enhancements to `global.js` include modal handling logic for improved UI interaction. This aids in dynamically loading required scripts, enhancing user experience in courses with exp360 activities. --- db/events.php | 5 +++++ global.js | 23 +++++++++++++++++++++++ lib.php | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 db/events.php diff --git a/db/events.php b/db/events.php new file mode 100644 index 0000000..3ed930f --- /dev/null +++ b/db/events.php @@ -0,0 +1,5 @@ + + + + +`; + + // Append the modal HTML to the document body + document.body.insertAdjacentHTML('beforeend', modalHTML); + // Function to load a script into the DOM function loadScript(url, integrity, crossorigin) { return new Promise((resolve, reject) => { diff --git a/lib.php b/lib.php index 6ed97d7..da71247 100644 --- a/lib.php +++ b/lib.php @@ -56,3 +56,44 @@ function mod_exp360_cm_info_dynamic(cm_info $cm) $cm->set_no_view_link(); $cm->set_content($script); } + +/** + * Event observer for mod_exp360. + */ +function mod_exp360_event_observer($event) +{ + global $PAGE, $DB; + + // Get the course ID from the event. + $courseid = $event->courseid; + + // Check if the course contains any instances of the exp360 activity. + $sql = "SELECT COUNT(*) + FROM {course_modules} cm + JOIN {modules} m ON cm.module = m.id + JOIN {exp360} e ON cm.instance = e.id + WHERE cm.course = :courseid + AND m.name = 'exp360'"; + $params = ['courseid' => $courseid]; + $count = $DB->count_records_sql($sql, $params); + + // If the course contains at least one instance of exp360, inject the JavaScript. + if ($count > 0) { + $PAGE->requires->js('/mod/exp360/global.js'); + } +} + +/** + * Returns the list of event observers. + * + * @return array + */ +function mod_exp360_get_event_observers() +{ + return [ + [ + 'eventname' => '\core\event\course_viewed', + 'callback' => 'mod_exp360_event_observer', + ], + ]; +}