root/src/public/js/DragAndDrop.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var DragAndDrop = (function() {
    var bind = function(el, callback) {
        if (!el || !callback) {
            throw "DragAndDrop.bind needs target element and callback";
        }

        var dragOver = function(e) {e.preventDefault();return false;};
        var drop = function(e) {
            e.preventDefault();
            // tested in icecat
            var uri = null;
            try {
                uri = e.originalEvent.dataTransfer.getData("text/uri-list");
            } catch (e) {};

            if (uri) {
                callback(uri);
            } else {
                // only works in chrome
                e.originalEvent.dataTransfer.items[0].getAsString(function(url) {
                    callback(url)
                });
            }
        };
        var listeners = [dragOver, drop];

        $(el).on('dragover', dragOver);
        $(el).on('drop', drop);

        return listeners;
    }

    var unbind = function(el, listeners) {
        if (listeners instanceof Array) {
            return listeners.map(function(t) {
                return [
                    $(el).unbind("dragover", t),
                    $(el).unbind("drop", t)
                ];
            });
        } else if (listeners === "all") {
            return [
                listeners.unbind("dragover"),
                listeners.unbind("drop")
            ]
        } else {
            throw "give [functions] to unbind or the string \"all\" to unbind all";
        }
    }

    return {
        bind: bind,
        unbind: unbind
    }
})();