【问题标题】:Queued message sending with Prototype.AJAX使用 Prototype.AJAX 发送队列消息
【发布时间】:2010-08-09 09:25:18
【问题描述】:

是否有任何最佳实践模式来实现发送有序请求的队列?我知道这触及了异步请求背后的逻辑,但在特殊情况下需要排队发送:)

这是我的第一次尝试:

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)
    });
},

有没有更好的实现方式? 提前谢谢你:)

【问题讨论】:

    标签: javascript ajax queue prototypejs design-patterns


    【解决方案1】:

    不要一个人死!!我认为你的类/命名空间可能有点混乱,因为你的混合 : 和 = (你不能在对象 {} 命名空间内使用 =)

    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()
                    }
                });
            }
        }
    }
    

    要测试的代码

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

    用真正的大文件或慢速脚本试试这个,你会看到队列功能正常工作。

    【讨论】:

      猜你喜欢
      • 2017-02-07
      • 2020-04-05
      • 1970-01-01
      • 2014-01-28
      • 2020-01-01
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 2016-05-02
      相关资源
      最近更新 更多