Search code examples
backbone.jsbackbone-views

How to call fetch method of Backbone Collection passing Id


I want to fire fetch method on Backbone Collection which would pass an Id parameter similar to what happens in Model.fetch(id)

E.g.

var someFoo= new Foo({id: '1234'});// Where Foo is a Backbone Model
someFoo.fetch();

My Backbone collection:-

var tasks = backbone.Collection.extend({
    model: taskModel,
    url: '/MyController/GetTasks',
    initialize: function () {
        return this;
    }
});

In my View when I try to fetch data:-

var _dummyId = 10; //

// Tried approach 1 && It calls an api without any `id` parameter, so I get 500 (Internal Server Error).
this.collection.fetch(_dummyId); 


// Tried approach 2 && which fires API call passing Id, but just after that 
// I am getting error as below:- Uncaught TypeError: object is not a function
this.collection.fetch({
    data: {
        id: _dummyId
    }
});

Found it very late : To cut short the above story I want something like Get /collection/id in backbone.


Solution

  • Thank you for your answers, finally I got the solution from Backbone.js collection options.

    Apologies that I couldn't explain the question properly while for same requirement others have done brilliantly and smartly.

    Solution : I can have something like :-

    var Messages = Backbone.Collection.extend({
      initialize: function(models, options) {
        this.id = options.id;
      },
      url: function() {
        return '/messages/' + this.id;
      },
      model: Message,
    });
    
    var collection = new Messages([], { id: 2 });
    collection.fetch();
    

    Thanks to nrabinowitz. Link to the Answer