Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
Tim Brunsmo Avatar asked Apr 03 '12 19:04

Tim Brunsmo


2 Answers

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/

like image 189
nikoshr Avatar answered Nov 07 '22 23:11

nikoshr


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.

like image 39
abraham Avatar answered Nov 08 '22 00:11

abraham