0

Hi I'll need your help on the following:

I've defined Backbone Collection which acts as a linked list: each Model in the Collection has a reference to its predecessor as well as successor.

Inserting a new Model into the Collection triggers an event which updates both predecessor and successor Model to refer to the newly inserted Model and stores these Models to database.

The sequence of Models is key and the application must remain stateless.

The problem: When a nervous user presses the add button rapidly I find the database shows more Model instances then are found in my application. (I expect this is due to async AJAX calls to the database)

I have considered overwriting the models save function and execute the Models update in one AJAX call, queuing the Models save calls via callbacks.

However I think I'm barking up the wrong tree and expect there is better solution for this problem.

Your help is much appreciated.

1 Answers1

1

The simplest solution is to disable the add button, until the previous request has completed. Let's assume you have a view with an #add button:

addClicked: function(e) {
  var $add = this.$("#add");
  var model = new Model(this.parseAttributesFromView()); //or something...

  //disable add button
  $add.attr('disabled', true);

  model.save().done(function() {
    //enable add button after save succeeds
    $add.attr('disabled', false);
  });
}

Alternatively you can debounce your click event handler so that it can only be executed once per n milliseconds:

//only allow add once every 100ms
addClicked: _.debounce(function() {
  //..
}, 100, true)

In any case implementing a packet or queue based solution seems overkill, if you can solve the issue at the view level.

jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • Looking at further requirements I've decided to have register the sequence in a separate Model. Thanks for your help. – user1833790 Jan 29 '13 at 17:57