开发者

Queued message sending with Prototype.AJAX

is there any best-practice-pattern for implementing a queue for sending ordered requests? I know this hits the logic behind ansynchronous requests, but in special cases one needs queued sending :)

Here is my fi开发者_StackOverflow社区rst attempt:

this.queue = [],
this.sending = false,  
send: function(message) {
    if (this.sending) {
        this.queue.push(message);
    } else {
        else this.push(message);
    }
},
push: function(message) {
    this.sending = true;
    new Ajax.Request(this.outURL + "&message=" + encodeURIComponent(message), {
        onSuccess: function() {
            this.sending = false;
            if (this.queue.size() > 0) {
                this.push("queued: " + this.queue.shift());
            }
        }.bind(this)
    });
},

Is there any better implementation? Thank you in advance :)


Do not die alone!! I think your class/namespace may be a little messed up since your mixing : and = (you cannot use = inside of an object {} namespace )

AjaxQueue = {
    outURL: '/ajax.html',
    queue: [],
    sending: false,

    //Stick message on the queue array
    send: function(message) {
        this.queue.push(message);
        this.iterate();
    },
    //If theres a message on the queue array send it, then recursively calls itself
    iterate: function() {
        message = this.queue.pop()
        //this will be false and stop recursion when there are no more messages
        if (message)
        {
            new Ajax.Request(this.outURL, {
                //no need to use string appending or encodeURL, prototype does this for you
                parameters: {message: message},
                method: 'GET',
                onSuccess: function() {
                    //recursion.  We avoid this because it wont be in scope
                    AjaxQueue.iterate()
                }
            });
        }
    }
}

Code to test

AjaxQueue.send('First Message'); AjaxQueue.send('Second message'); AjaxQueue.send('Third Message')

Try this with a real big file or slow script and you'll see the queue functionality work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜