weekly release 4.0dev
[moodle.git] / mod / forum / amd / src / subscription_toggle.js
CommitLineData
2646e9d6
RW
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 * Handle discussion subscription toggling on a discussion list in
18 * the forum view.
19 *
20 * @module mod_forum/subscription_toggle
2646e9d6
RW
21 * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24define([
25 'jquery',
26 'core/templates',
27 'core/notification',
28 'mod_forum/repository',
29 'mod_forum/selectors',
1a9e5cb2
JP
30 'core/pubsub',
31 'mod_forum/forum_events',
2646e9d6
RW
32 ], function(
33 $,
34 Templates,
35 Notification,
36 Repository,
1a9e5cb2
JP
37 Selectors,
38 PubSub,
49f5b16c 39 ForumEvents
2646e9d6
RW
40 ) {
41
42 /**
43 * Register event listeners for the subscription toggle.
44 *
45 * @param {object} root The discussion list root element
49f5b16c
RW
46 * @param {boolean} preventDefault Should the default action of the event be prevented
47 * @param {function} callback Success callback
2646e9d6 48 */
49f5b16c 49 var registerEventListeners = function(root, preventDefault, callback) {
2646e9d6
RW
50 root.on('click', Selectors.subscription.toggle, function(e) {
51 var toggleElement = $(this);
52 var forumId = toggleElement.data('forumid');
53 var discussionId = toggleElement.data('discussionid');
54 var subscriptionState = toggleElement.data('targetstate');
55
56 Repository.setDiscussionSubscriptionState(forumId, discussionId, subscriptionState)
57 .then(function(context) {
1a9e5cb2
JP
58 PubSub.publish(ForumEvents.SUBSCRIPTION_TOGGLED, {
59 discussionId: discussionId,
60 subscriptionState: subscriptionState
61 });
49f5b16c 62 return callback(toggleElement, context);
959b996c
JP
63 })
64 .catch(Notification.exception);
65
49f5b16c
RW
66 if (preventDefault) {
67 e.preventDefault();
68 }
959b996c 69 });
2646e9d6
RW
70 };
71
72 return {
49f5b16c 73 init: registerEventListeners
2646e9d6
RW
74 };
75});