user577808
user577808

Reputation: 2527

Backbone one-off ajax request

I have a simple List-style Backbone app that I'm making with a Rails backend.

I have a collection:

var ItemList = Backbone.Collection.extend({
  model: Item,

  initialize: function(id) {
    this.id = id;
  },

  url: function(){
    return '/lists/' + this.id + '/items';
  },

});

All the standard CRUD operations work fine from the model. But I have an "extra" route - "clear" that will clear all the items in a list at one show. The route would be:

/lists/[:id]/clear

Because this is outside the normal CRUD operations, is there way to hook it into the normal Collection, or do i do something separate?

Upvotes: 0

Views: 1158

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 145994

You can make a method on your collection called destroy and inside there you can take one of several approaches to making the AJAX request (in order of harmony with Backbone). Note you probably don't want to call your collection method clear because Backbone Models already have a clear method with different semantics.

  1. create a throw-away Backbone.Model instance with the correct URL and ID and then call 'destroy' on it
  2. Call Backbone.sync with method "delete" and a throw-away model object with just an 'url' property and empty 'toJSON' function with the right ID
  3. Make a direct jQuery $.ajax call.

Upvotes: 2

mu is too short
mu is too short

Reputation: 434606

You could add your own method that executes /lists/:id/clear and then does a reset on the collection when it is done:

clear: function() {
    var _this = this;
    $.ajax({
        url: '/lists/' + this.id + '/clear',
        //...
        success: function() {
            _this.reset();
        }
    });
}

When you call reset without any arguments, it removes all the models from the collection.

Upvotes: 2

Related Questions