본문 바로가기

WebDev

tosync.js

tosync.js

merge async callback

example

following example shows how to use this library

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p id="a">initial</p>
<script src="tosync.js"></script>
<script>
    tosync.register('a', 3, function (hstore) {
        document.querySelector('p').innerText = JSON.stringify(hstore);
    }, function (e) {
        console.log(e);
    });
    tosync.report('a', 'x', 1);
    tosync.report('a', 'b', 1);
    tosync.report('a', 'c', 1);
</script>
</body>
</html>

soucre

var tosync = (function () {
    "use strict";
    var dict = {};
    var nothing = function () {
    };
    var register = function (name, countdown, success, fail, timeout) {
        dict[name] = {
            countdown: countdown,
            success: success,
            fail: (typeof fail === 'undefined') ? nothing : fail,
            hstore: {},
            timeout: (typeof timeout === 'undefined') ? 0 : timeout
        };
        if (timeout) {
            setTimeout(function () {
                if (countdown > 0) {
                    fail(new Error('timeout'));
                }
            }, timeout);
        }
    };

    var unregister = function (name) {
        delete dict[name];
    };

    var report = function (name, key, value) {
        var d = dict[name];
        d.hstore[key] = value;
        d.countdown -= 1;
        if (d.countdown <= 0) {
            try {
                d.success(d.hstore);
            }
            catch (e) {
                d.fail(e);
            }
            unregister(name);
        }
    };

    return {
        register: register,
        unregister: unregister,
        report: report
    }
})();

'WebDev' 카테고리의 다른 글

Django Foreign Key  (0) 2016.02.25
Require.js  (0) 2016.02.20
Chrome extension 개발  (0) 2016.02.16
Web SQL  (0) 2016.02.15
django custom user  (0) 2016.02.07