Ajax queue Backbone js

痞子三分冷 提交于 2019-12-30 08:10:05

问题


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.


回答1:


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/




回答2:


User debounce from underscore.js.

Creates and returns a new debounced version of the passed function that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.

This way it will only fire once after the last blur event.



来源:https://stackoverflow.com/questions/10000352/ajax-queue-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!