Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 254
Shubh Avatar asked Dec 26 '22 17:12

Shubh


2 Answers

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

like image 197
Shubh Avatar answered Dec 28 '22 05:12

Shubh


As mentioned by Matt Ball, the question doesn't make sense: either you call fetch() on a Collection to retrieve all the Models from the Server, or you call fetch() on a Model with an ID to retrieve only this one.

Now, if for some reason you'd need to pass extra parameters to a Collection.fetch() (such as paging information), you could always add a 'data' key in your options object, and it may happen that one of this key be an id (+add option to add this fetched model rather than replace the collection with just one model)... but that would be a very round-about way of fetching a model. The expected way is to create a new Model with the id and fetch it:

this.collection = new taskCollection();
newTask = this.collection.add({id: 15002});
newTask.fetch();

In your code however, I don't see where the ID is coming from, so I am wondering what did you expect to be in the 'ID' parameter that you wanted the collection.fetch() to send?

like image 21
Enders Avatar answered Dec 28 '22 07:12

Enders