如何调用传递Id的Backbone Collection的fetch方法

Shu*_*ubh 4 backbone.js backbone-views

我想fetch在Backbone Collection上触发方法,它会传递类似于发生的Id参数Model.fetch(id)

例如

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

我的Backbone系列: -

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

在我的视图中,当我尝试获取数据时: -

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
    }
});
Run Code Online (Sandbox Code Playgroud)

发现它很晚:为了缩短上面的故事我想要像骨干中的Get/collection/id这样的东西.

Shu*_*ubh 9

感谢您的回答,最后我从Backbone.js集合选项中获得了解决方案.

抱歉,我无法正确地解释这个问题,而对于同样的要求,其他人已经做得非常聪明.

解决方案:我可以有类似的东西: -

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();
Run Code Online (Sandbox Code Playgroud)

谢谢nrabinowitz.链接到答案