如何将信息发送到新实例化的主干集合

How to send information to a newly instantiated Backbone collection?

本文关键字:实例化 集合 信息      更新时间:2023-09-26

我有一个API,它根据URL中的ID过滤一组对象,如下所示:

http://localhost:8000/api/v1/goal_update/?goal__id=12&format=json

我有一个集合,它对上面的URL执行GET请求。这是集合的代码:

  var GoalUpdateList = Backbone.Collection.extend({
    // Reference the Goal Update model
    model: GoalUpdate,
    // Do HTTP requests on this endpoint
    url: function() {
      return "http://localhost:8000/api/v1/goal_update/?goal__id=" + this.goal_id + "&format=json";
    },
    // Set the goal ID that the goal update list corresponds to
    initialize: function(goal_id) {
      this.goal_id = goal_id;
    },
  });

我想在创建集合的新实例时传入ID,所以我创建了一个包含以下代码的视图:

this.collection = new GoalUpdateList(this.model.get("id"));

不过,它认为我在传递模型参数。我试图传递信息,告诉集合要使用什么URL。因此,它通过一个验证函数运行ID,并将其余的主干代码搞砸。

Backbone的集合期望模型数据作为第一个参数,正如您已经注意到的那样。但是,您可以像其他Backbone对象一样,将第二个参数指定为对象文字。只需传递nullundefined作为第一个参数,然后在集合initialize方法中,获得options作为第二个参数。


GoalUpdateList = Backbone.Collection.extend({
  initialize: function(data, options){
    this.goal_id = options.goal_id;
  }
});
new GoalUpdateList(null, model.get("goal_id"));