Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
define([], function() {
17
 
18
    /**
19
     * When embedded the communicator helps talk to the parent page.
20
     * This is a copy of the H5P.communicator, which we need to communicate in this context
21
     */
22
    var H5PEmbedCommunicator = function() {
23
        this._actionHandlers = {};
24
        this.registerEventListeners();
25
    };
26
 
27
    /** @type {Object} Maps actions to functions. */
28
    H5PEmbedCommunicator.prototype._actionHandlers = {};
29
 
30
    /**
31
     * Register action listener.
32
     *
33
     * @param {string} action What you are waiting for
34
     * @param {function} handler What you want done
35
     */
36
    H5PEmbedCommunicator.prototype.on = function(action, handler) {
37
        this._actionHandlers[action] = handler;
38
    };
39
 
40
    /**
41
     * Send a message to the all mighty father.
42
     *
43
     * @param {string} action
44
     * @param {Object} [data] payload
45
     */
46
    H5PEmbedCommunicator.prototype.send = function(action, data) {
47
        if (data === undefined) {
48
            data = {};
49
        }
50
        data.context = 'h5p';
51
        data.action = action;
52
 
53
        // Parent origin can be anything.
54
        window.parent.postMessage(data, '*');
55
    };
56
 
57
 
58
    /**
59
     * Register event listeners for the communicator.
60
     *
61
     * @method registerEventListeners
62
     */
63
    H5PEmbedCommunicator.prototype.registerEventListeners = function() {
64
        var self = this;
65
        // Register message listener.
66
        window.addEventListener('message', function receiveMessage(event) {
67
            if (window.parent !== event.source || event.data.context !== 'h5p') {
68
                return; // Only handle messages from parent and in the correct context.
69
            }
70
 
71
            if (self._actionHandlers[event.data.action] !== undefined) {
72
                self._actionHandlers[event.data.action](event.data);
73
            }
74
        }, false);
75
    };
76
 
77
    return new H5PEmbedCommunicator();
78
 
79
});