Dojo XHR & AOP

How to do something while a dojo xhr request is waiting or loading: http://stackoverflow.com/questions/8512483/how-to-do-something-while-a-dojo-xhr-request-is-waiting-or-loading

by phusick

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dijit/themes/claro/claro.css">
<body class="claro">
    <button id="sendBtn" data-dojo-type="dijit.form.Button">Send</button>
    <span id="output"></span>
</body>

JavaScript

dojo.require("dojox.timing");
dojo.require("dijit.form.Button");

dojo.declare("phusick.Form", null, {

    send: function() {
        var def = dojo.xhrPost({
            url: "/echo/json/",
            content: {
                json: dojo.toJson({data: "some data"})
            },
            handleAs: "json"
        });
        
        def.addCallback(this, "onSendSuccess");
        this.onSend();
    },
    
    onSend: function() {
        console.time("console timer");
        console.log("sending...");
    },
    
    onSendSuccess: function(result) {
        console.log("sent: " + dojo.toJson(result));
        console.timeEnd("console timer");
    } 
});

dojo.declare("phusick.Observer", null, {

    observe: function(form) {
        this.form = form;
        this.interval = 5;
        this.timer = new dojox.timing.Timer(this.interval);
        dojo.connect(this.timer, "onStart", this, function() {this.timeElapsed = 0});
        dojo.connect(this.timer, "onTick", this, "onTick");
        dojo.connect(form, "onSend", this.timer, "start");
        dojo.connect(form, "onSendSuccess", this.timer, "stop");
    },
    
    onTick: function() {
        this.timeElapsed += this.interval;
        dojo.byId("output").innerHTML = this.timeElapsed + " ms";
        console.log(this.timeElapsed + " ms");
    }
    
});


dojo.ready(function() {
    var form = new phusick.Form();
    var observer = new phusick.Observer();
    observer.observe(form);
    
    dojo.connect(dijit.byId("sendBtn"), "onClick", function() {
        form.send();
    });
    
});