2012-04-03 64 views
0

我有一個Backbone集合,其URL取決於初始化函數。當我創建這個Backbone集合的實例時,我傳入一個ID來過濾模型的哪些實例出現。以下是代碼的樣子:Backbone集合的URL取決於初始化函數

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

    }); 

當然,這是行不通的。 this.goal_id被視爲未定義。我猜是因爲在初始化函數運行之前設置了URL。

回答

4

您可以使用動態構建URL的url函數。

url: function() { 
    return "http://localhost:8000/api/v1/goal_update/?goal__id=" + this.goal_id + "&format=json"; 
},