Ajax 队列 Backbone js [英] Ajax queue Backbone js

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

问题描述

我在 Rails 3.2.2 上运行 Backbone js 0.9.2,我有一个用于添加成本行的页面.成本有 3 个文本字段:标题、描述和价格.

我正在节省模糊处理的每一项成本.

model.save() 以非常短的间隔被多次调用.它发出一个 create(post) 请求,然后发出一个 update(put) 请求.我遇到的问题是 PUT 请求有时会在 POST 之前到达服务器,结果是该模型被创建并持久化了两次(重复).

为了节省模糊是请求的行为,所以我需要一种方法来排队请求.我读过一些关于 Spine js 的内容,他们通过某种队列解决了这个问题.我还查看了 this,但似乎无法弄清楚这一点.

感觉这应该是一个常见问题,使用单页应用程序"但找不到任何相关信息.

解决方案

您可以覆盖 save 方法并使用 延迟对象.例如,

var MDef = Backbone.Model.extend({url: "/echo/json/?delay=3",初始化:函数(){this.queue = $.Deferred();this.queue.resolve();},保存:功能(属性,选项){var m = 这个;console.log("set "+JSON.stringify(attrs));//this.queue = this.queue.pipe with jquery<1.8this.queue = this.queue.then(function() {console.log("请求"+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({价格: "一个价格"});

还有一个小提琴:http://jsfiddle.net/nikoshr/8nEUm/>

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() 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).

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

And a Fiddle : http://jsfiddle.net/nikoshr/8nEUm/

这篇关于Ajax 队列 Backbone js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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