weekly release 3.4dev
[moodle.git] / calendar / amd / src / view_manager.js
CommitLineData
695c5726
AN
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * A javascript module to handler calendar view changes.
18 *
19 * @module core_calendar/view_manager
20 * @package core_calendar
21 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
a4af4c96
SL
24define(['jquery', 'core/templates', 'core/notification', 'core_calendar/repository', 'core_calendar/events'],
25 function($, Templates, Notification, CalendarRepository, CalendarEvents) {
695c5726
AN
26
27 var SELECTORS = {
28 ROOT: "[data-region='calendar']",
29 CALENDAR_NAV_LINK: "span.calendarwrapper .arrow_link",
30 CALENDAR_MONTH_WRAPPER: ".calendarwrapper",
31 };
32
33 /**
34 * Register event listeners for the module.
35 *
36 * @param {object} root The root element.
37 */
38 var registerEventListeners = function(root) {
39 root = $(root);
40
836aa3f6 41 root.on('click', SELECTORS.CALENDAR_NAV_LINK, function(e) {
695c5726
AN
42 var courseId = $(root).find(SELECTORS.CALENDAR_MONTH_WRAPPER).data('courseid');
43 var link = $(e.currentTarget);
44 changeMonth(link.attr('href'), link.data('time'), courseId);
45
46 e.preventDefault();
47 });
48 };
49
695c5726
AN
50 /**
51 * Handle changes to the current calendar view.
52 *
a4af4c96 53 * @param {String} url The calendar url to be shown
695c5726
AN
54 * @param {Number} time The calendar time to be shown
55 * @param {Number} courseid The id of the course whose events are shown
56 */
57 var changeMonth = function(url, time, courseid) {
58 CalendarRepository.getCalendarMonthData(time, courseid)
59 .then(function(context) {
a4af4c96 60 window.history.pushState({}, '', url);
695c5726
AN
61 return Templates.render('core_calendar/month_detailed', context);
62 })
63 .then(function(html, js) {
836aa3f6 64 return Templates.replaceNodeContents(SELECTORS.CALENDAR_MONTH_WRAPPER, html, js);
695c5726 65 })
a4af4c96 66 .done(function() {
836aa3f6 67 $('body').trigger(CalendarEvents.monthChanged, [time, courseid]);
695c5726
AN
68 })
69 .fail(Notification.exception);
70 };
71
72 return {
73 init: function() {
74 registerEventListeners(SELECTORS.ROOT);
75 }
76 };
77 });