Backbone collection's URL depends on initialize function

Go To


I have a Backbone collection whose URL depends on the initialize function. When I create an instance of this Backbone collection, I pass in an ID to filter which instances of the model appear. Here is what the collection's code looks like:

  var GoalUpdateList = Backbone.Collection.extend({

    // Reference the Goal Update model
    model: GoalUpdate,

    // Do HTTP requests on this endpoint
    url: "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;


Of course, this doesn't work. this.goal_id is seen as being undefined. I guess because the URL is set before the initialization function is run.

2012-04-03 23:19
by egidra


You can use a function for url that dynamically builds the URL.

url: function() {
  return "http://localhost:8000/api/v1/goal_update/?goal__id=" + this.goal_id + "&format=json";
2012-04-03 23:25
by abraham