MDL-59751 core_calendar: move code to avoid duplication
authorSimey Lameze <simey@moodle.com>
Fri, 29 Sep 2017 05:05:15 +0000 (13:05 +0800)
committerSimey Lameze <simey@moodle.com>
Thu, 5 Oct 2017 06:23:02 +0000 (14:23 +0800)
calendar/amd/build/calendar.min.js
calendar/amd/build/crud.min.js [new file with mode: 0644]
calendar/amd/build/summary_modal.min.js
calendar/amd/src/calendar.js
calendar/amd/src/crud.js [new file with mode: 0644]
calendar/amd/src/summary_modal.js

index f9167a1..a48bd48 100644 (file)
Binary files a/calendar/amd/build/calendar.min.js and b/calendar/amd/build/calendar.min.js differ
diff --git a/calendar/amd/build/crud.min.js b/calendar/amd/build/crud.min.js
new file mode 100644 (file)
index 0000000..4e39179
Binary files /dev/null and b/calendar/amd/build/crud.min.js differ
index fdca2a5..dc451ba 100644 (file)
Binary files a/calendar/amd/build/summary_modal.min.js and b/calendar/amd/build/summary_modal.min.js differ
index ef43e41..a3e6936 100644 (file)
@@ -38,7 +38,9 @@ define([
             'core_calendar/summary_modal',
             'core_calendar/repository',
             'core_calendar/events',
-            'core_calendar/view_manager'
+            'core_calendar/view_manager',
+            'core_calendar/crud',
+            'core_calendar/selectors',
         ],
         function(
             $,
@@ -53,7 +55,9 @@ define([
             SummaryModal,
             CalendarRepository,
             CalendarEvents,
-            CalendarViewManager
+            CalendarViewManager,
+            CalendarCrud,
+            CalendarSelectors
         ) {
 
     var SELECTORS = {
@@ -192,29 +196,6 @@ define([
         }
     };
 
-    /**
-     * Create the event form modal for creating new events and
-     * editing existing events.
-     *
-     * @method registerEventFormModal
-     * @param {object} root The calendar root element
-     * @return {object} The create modal promise
-     */
-    var registerEventFormModal = function(root) {
-        var newEventButton = root.find(SELECTORS.NEW_EVENT_BUTTON);
-        var contextId = newEventButton.attr('data-context-id');
-
-        return ModalFactory.create(
-            {
-                type: ModalEventForm.TYPE,
-                large: true,
-                templateContext: {
-                    contextid: contextId
-                }
-            }
-        );
-    };
-
     /**
      * Listen to and handle any calendar events fired by the calendar UI.
      *
@@ -294,7 +275,7 @@ define([
                 .fail(Notification.exception);
         });
 
-        var eventFormPromise = registerEventFormModal(root);
+        var eventFormPromise = CalendarCrud.registerEventFormModal(root, CalendarSelectors.newEventButton);
         registerCalendarEventListeners(root, eventFormPromise);
 
         // Bind click event on the new event button.
@@ -353,7 +334,7 @@ define([
     return {
         init: function(root) {
             root = $(root);
-
+            CalendarCrud.init(root);
             CalendarViewManager.init(root);
             registerEventListeners(root);
         }
diff --git a/calendar/amd/src/crud.js b/calendar/amd/src/crud.js
new file mode 100644 (file)
index 0000000..49fe699
--- /dev/null
@@ -0,0 +1,195 @@
+// This file is part of Moodle - http://moodle.org/
+//
+// Moodle is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Moodle is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * A module to handle CRUD operations within the UI.
+ *
+ * @module     core_calendar/crud
+ * @package    core_calendar
+ * @copyright  2017 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+define([
+    'jquery',
+    'core/str',
+    'core/notification',
+    'core/custom_interaction_events',
+    'core/modal',
+    'core/modal_registry',
+    'core/modal_factory',
+    'core/modal_events',
+    'core_calendar/modal_event_form',
+    'core_calendar/repository',
+    'core_calendar/events',
+    'core_calendar/modal_delete',
+    'core_calendar/selectors',
+],
+function(
+    $,
+    Str,
+    Notification,
+    CustomEvents,
+    Modal,
+    ModalRegistry,
+    ModalFactory,
+    ModalEvents,
+    ModalEventForm,
+    CalendarRepository,
+    CalendarEvents,
+    ModalDelete,
+    CalendarSelectors
+) {
+
+    /**
+     * Prepares the action for the summary modal's delete action.
+     *
+     * @param {Number} eventId The ID of the event.
+     * @param {string} eventTitle The event title.
+     * @param {Number} eventCount The number of events in the series.
+     * @return {Promise}
+     */
+    function confirmDeletion(eventId, eventTitle, eventCount) {
+        var deleteStrings = [
+            {
+                key: 'deleteevent',
+                component: 'calendar'
+            },
+        ];
+
+        eventCount = parseInt(eventCount, 10);
+        var deletePromise;
+        var isRepeatedEvent = eventCount > 1;
+        if (isRepeatedEvent) {
+            deleteStrings.push({
+                key: 'confirmeventseriesdelete',
+                component: 'calendar',
+                param: {
+                    name: eventTitle,
+                    count: eventCount,
+                },
+            });
+
+            deletePromise = ModalFactory.create(
+                {
+                    type: ModalDelete.TYPE
+                }
+            );
+        } else {
+            deleteStrings.push({
+                key: 'confirmeventdelete',
+                component: 'calendar',
+                param: eventTitle
+            });
+
+
+            deletePromise = ModalFactory.create(
+                {
+                    type: ModalFactory.types.SAVE_CANCEL
+                }
+            );
+        }
+
+        deletePromise.then(function(deleteModal) {
+            deleteModal.show();
+
+            return;
+        })
+        .fail(Notification.exception);
+
+        var stringsPromise = Str.get_strings(deleteStrings);
+
+        var finalPromise = $.when(stringsPromise, deletePromise)
+        .then(function(strings, deleteModal) {
+            deleteModal.setTitle(strings[0]);
+            deleteModal.setBody(strings[1]);
+            if (!isRepeatedEvent) {
+                deleteModal.setSaveButtonText(strings[0]);
+            }
+
+            deleteModal.getRoot().on(ModalEvents.save, function() {
+                CalendarRepository.deleteEvent(eventId, false)
+                    .then(function() {
+                        $('body').trigger(CalendarEvents.deleted, [eventId, false]);
+                        return;
+                    })
+                    .catch(Notification.exception);
+            });
+
+            deleteModal.getRoot().on(CalendarEvents.deleteAll, function() {
+                CalendarRepository.deleteEvent(eventId, true)
+                    .then(function() {
+                        $('body').trigger(CalendarEvents.deleted, [eventId, true]);
+                        return;
+                    })
+                    .catch(Notification.exception);
+            });
+
+            return deleteModal;
+        })
+        .fail(Notification.exception);
+
+        return finalPromise;
+    }
+
+    /**
+     * Create the event form modal for creating new events and
+     * editing existing events.
+     *
+     * @method registerEventFormModal
+     * @param {object} root The calendar root element
+     * @param {object} newEventButton The new event button element
+     * @return {object} The create modal promise
+     */
+    var registerEventFormModal = function(root, newEventButton) {
+
+        var contextId = newEventButton.data('context-id');
+
+        return ModalFactory.create(
+            {
+                type: ModalEventForm.TYPE,
+                large: true,
+                templateContext: {
+                    contextid: contextId
+                }
+            }, [root, CalendarSelectors.newEventButton]
+        );
+    };
+    /**
+     * Register the listeners required to remove the event.
+     *
+     * @param   {jQuery} root
+     */
+    function registerRemove(root) {
+        root.on('click', CalendarSelectors.actions.remove, function(e) {
+            // Fetch the event title, count, and pass them into the new dialogue.
+            var eventSource = $(this);
+            var eventId = eventSource.data('eventId'),
+                eventTitle = eventSource.data('eventTitle'),
+                eventCount = eventSource.data('eventCount');
+            confirmDeletion(eventId, eventTitle, eventCount);
+
+            e.preventDefault();
+        });
+    }
+
+    return {
+        init: function(root) {
+            registerEventFormModal(root, $(CalendarSelectors.newEventButton));
+        },
+        registerRemove: registerRemove,
+        confirmDeletion: confirmDeletion,
+        registerEventFormModal: registerEventFormModal
+    };
+});
index ff9317f..5237ecb 100644 (file)
@@ -32,7 +32,7 @@ define([
     'core/modal_events',
     'core_calendar/repository',
     'core_calendar/events',
-    'core_calendar/modal_delete',
+    'core_calendar/crud',
 ],
 function(
     $,
@@ -45,7 +45,7 @@ function(
     ModalEvents,
     CalendarRepository,
     CalendarEvents,
-    ModalDelete
+    CalendarCrud
 ) {
 
     var registered = false;
@@ -110,6 +110,18 @@ function(
         return this.getBody().find(SELECTORS.ROOT).attr('data-event-id');
     };
 
+    /**
+     * Get the title for the event being shown in this modal. This value is
+     * not cached because it will change depending on which event is
+     * being displayed.
+     *
+     * @method getEventTitle
+     * @return {String}
+     */
+    ModalEventSummary.prototype.getEventTitle = function() {
+        return this.getBody().find(SELECTORS.ROOT).attr('data-event-title');
+    };
+
     /**
      * Get the number of events in the series for the event being shown in
      * this modal. This value is not cached because it will change
@@ -154,8 +166,18 @@ function(
         // We have to wait for the modal to finish rendering in order to ensure that
         // the data-event-title property is available to use as the modal title.
         this.getRoot().on(ModalEvents.bodyRendered, function() {
-            var eventTitle = this.getBody().find(SELECTORS.ROOT).attr('data-event-title');
-            prepareDeleteAction(this, eventTitle);
+            this.getDeleteButton().data({
+                eventTitle: this.getEventTitle(),
+                eventId: this.getEventId(),
+                eventCount: this.getEventCount(),
+            });
+            CalendarCrud.registerRemove(this.getModal(), SELECTORS.ROOT);
+
+        }.bind(this));
+
+        $('body').on(CalendarEvents.deleted, function() {
+            // Close the dialogue on delete.
+            this.hide();
         }.bind(this));
 
         CustomEvents.define(this.getEditButton(), [
@@ -163,7 +185,6 @@ function(
         ]);
 
         this.getEditButton().on(CustomEvents.events.activate, function(e, data) {
-
             if (this.isActionEvent()) {
                 // Action events cannot be edited on the event form and must be redirected to the module UI.
                 $('body').trigger(CalendarEvents.editActionEvent, [this.getEditUrl()]);
@@ -184,90 +205,6 @@ function(
         }.bind(this));
     };
 
-    /**
-     * Prepares the action for the summary modal's delete action.
-     *
-     * @param {ModalEventSummary} summaryModal The summary modal instance.
-     * @param {string} eventTitle The event title.
-     */
-    function prepareDeleteAction(summaryModal, eventTitle) {
-        var deleteStrings = [
-            {
-                key: 'deleteevent',
-                component: 'calendar'
-            },
-        ];
-
-        var eventCount = parseInt(summaryModal.getEventCount(), 10);
-        var deletePromise;
-        var isRepeatedEvent = eventCount > 1;
-        if (isRepeatedEvent) {
-            deleteStrings.push({
-                key: 'confirmeventseriesdelete',
-                component: 'calendar',
-                param: {
-                    name: eventTitle,
-                    count: eventCount,
-                },
-            });
-
-            deletePromise = ModalFactory.create(
-                {
-                    type: ModalDelete.TYPE
-                },
-                summaryModal.getDeleteButton()
-            );
-        } else {
-            deleteStrings.push({
-                key: 'confirmeventdelete',
-                component: 'calendar',
-                param: eventTitle
-            });
-
-            deletePromise = ModalFactory.create(
-                {
-                    type: ModalFactory.types.SAVE_CANCEL
-                },
-                summaryModal.getDeleteButton()
-            );
-        }
-
-        var eventId = summaryModal.getEventId();
-        var stringsPromise = Str.get_strings(deleteStrings);
-
-        $.when(stringsPromise, deletePromise)
-        .then(function(strings, deleteModal) {
-            deleteModal.setTitle(strings[0]);
-            deleteModal.setBody(strings[1]);
-            if (!isRepeatedEvent) {
-                deleteModal.setSaveButtonText(strings[0]);
-            }
-
-            deleteModal.getRoot().on(ModalEvents.save, function() {
-                CalendarRepository.deleteEvent(eventId, false)
-                    .then(function() {
-                        $('body').trigger(CalendarEvents.deleted, [eventId, false]);
-                        summaryModal.hide();
-                        return;
-                    })
-                    .catch(Notification.exception);
-            });
-
-            deleteModal.getRoot().on(CalendarEvents.deleteAll, function() {
-                CalendarRepository.deleteEvent(eventId, true)
-                    .then(function() {
-                        $('body').trigger(CalendarEvents.deleted, [eventId, true]);
-                        summaryModal.hide();
-                        return;
-                    })
-                    .catch(Notification.exception);
-            });
-
-            return deleteModal;
-        })
-        .fail(Notification.exception);
-    }
-
     // Automatically register with the modal registry the first time this module is imported so that you can create modals
     // of this type using the modal factory.
     if (!registered) {