egidra
egidra

Reputation: 9087

How to send information to a newly instantiated Backbone collection?

I have an API that filters a set of objects based on the ID present in the URL, like so:

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

I have a collection that does a GET request on the above URL. Here is the code for the collection:

  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;
    },

  });

I want to pass in the ID when I create a new instance of the collection, so I created a view that has this code:

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

It thinks that I am passing in model parameters, though. I am trying to pass in information that tells the collection what URL to use. So it runs the ID through a validate function and messes up the rest of the backbone code.

Upvotes: 1

Views: 319

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72868

Backbone's collections expect model data as the first parameter, as you've already noted. But you can specify a second parameter as an object literal, like other Backbone objects. Just pass null or undefined as the first parameter, and then in your collection initialize method, get the options as the second parameter.


GoalUpdateList = Backbone.Collection.extend({

  initialize: function(data, options){
    this.goal_id = options.goal_id;
  }

});

new GoalUpdateList(null, model.get("goal_id"));

Upvotes: 4

Related Questions