util.js 2.33 KB
Newer Older
Dányi Bence committed
1
var cloud = (function(cloud) {
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

    function getCookie(name) {
        var cookieValue = null;
        if(document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for(var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if(cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    function csrfSafeMethod(method) {
        return(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        crossDomain: false,
        beforeSend: function(xhr, settings) {
            if(!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

Dányi Bence committed
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    /**
     * Convert bytes to human readable format
     */
    cloud.convert = function(n, skip, precision) {
        skip = skip | 0;
        precision = precision | 2;
        var suffix = 'B KB MB GB'.split(' ');
        for(var i = skip; n > 1024; i++) {
            n /= 1024;
        }
        return n.toFixed(precision) + ' ' + suffix[i];
    }

    /**
     * Returns throttled function
     */
    cloud.throttle = function(f) {
        var disabled = false;
        return function() {
            if(disabled) {
                return
            };
            disabled = true;
            setTimeout(function() {
                disabled = false;
            }, 700);
            f.apply(this, arguments);
        }
    }

    /**
     * Delay the function call for `f` until `g` evaluates true
     * Default check interval is 1 sec
     */
    cloud.delayUntil = function(f, g, timeout) {
        var timeout = timeout || 1000;

        function check() {
            var o = arguments;
            if(!g()) {
                setTimeout(function() {
                    check.apply(null, o)
                }, timeout);
                return;
            }
            f.apply(null, o);
        }
        return function() {
            check.apply(null, arguments);
        }
    }
Dányi Bence committed
82
    return cloud;
Dányi Bence committed
83
})(cloud || {});