Reputation: 9087
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;
console.log(this.goal_id);
console.log(this.url);
},
});
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.
Upvotes: 0
Views: 1485
Reputation: 47833
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";
},
Upvotes: 4