Search code examples
ruby-on-railsajaxbackbone.jsruby-on-rails-3.2

Ajax queue Backbone js


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.


Solution

  • 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/