阿贾克斯队列骨干JS [英] Ajax queue Backbone js

查看:207
本文介绍了阿贾克斯队列骨干JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我on Rails的3.2.2运行骨干JS 0.9.2,我有增加成本rows.A成本页面有3个文本域:标题,描述和价格

I am running Backbone js 0.9.2 on Rails 3.2.2,I have a page for adding cost rows.A cost have 3 TextFields: title, description and price.

我的模糊保存每个成本。

I am saving each cost on blur.

model.save()被调用多次以非常短的时间间隔。哪些问题有一个创建(POST)请求,那么一个更新(放)请求不久出现后。我遇到的问题是,PUT请求有时到达服务器开机自检,结果被该模型被创建并持续两次(重复)之前。

model.save() gets called multiple times with very short intervals. Which issues one create(post) request then one update(put) request shortly there after. The problem I am experiencing is that PUT request sometimes reaches the server before the POST, the result being that model gets created and persisted twice(duplicates).

要节省模糊是请求的行为,所以我需要一种方法来排队的请求。 我读过一些关于脊柱JS,他们解决一些类型的队列中。我也期待在来这个,但似乎无法想出解决办法。

To save on blur is the requested behavior, so I need a way to queue up requests. I have read something about Spine js, and that they solve it by some kind of queue. I've also looked in to this, but can't seem to figure this out.

这感觉就像这应该是一个常见的​​问题,以单页的应用程序的工作,但找不到任何关于它。

It feels like this should be a common issue, working with "single-page-apps" but can't find anything about it.

推荐答案

您可以覆盖保存方法,并与创建队列的延期对象。例如,

You could override the save method and create a queue with a deferred object . For example,

var MDef = Backbone.Model.extend({
    url: "/echo/json/?delay=3",

    initialize: function() {
        this.queue = $.Deferred();
        this.queue.resolve();
    },

    save: function(attrs,options) {
        var m = this; 
        console.log("set "+JSON.stringify(attrs));

        // this.queue = this.queue.pipe with jquery<1.8
        this.queue = this.queue.then(function() {
            console.log("request "+JSON.stringify(attrs));
            return Backbone.Model.prototype.save.call(m, attrs, options);
        });            
    }
});

var m = new MDef();
m.save({title: "a title"});
m.save({description: "a description"});
m.save({price: "a price"});

和一个小提琴: http://jsfiddle.net/nikoshr/8nEUm/

这篇关于阿贾克斯队列骨干JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆