How to call fetch method of Backbone Collection passing Id

时光毁灭记忆、已成空白 提交于 2019-12-23 13:36:05

问题


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.


回答1:


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




回答2:


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?



来源:https://stackoverflow.com/questions/20305882/how-to-call-fetch-method-of-backbone-collection-passing-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!