2012-09-02 130 views
0

this.id在Blog.Collections.Posts類中未定義。怎麼了?通過編號查找骨幹集合

博客收集

Blog.Collections.Posts = Backbone.Collection.extend({ 

    model: Blog.Models.Post, 
    url: function() { 
    console.log(this.id); 
    if (this.id) { 
     return '/api/posts/'+this.id 
    } 
    else{ 
     return '/api/posts' 
    } 
    } 

}); 

我的路由器:

Blog.Routers.Posts = Backbone.Router.extend({ 

    routes: { 
    ""     :  "index", 
    "entry/:id" :  "show" 
    }, 

    show: function(id) { 
    var collection = new Blog.Collections.Posts({id: id}); 
    collection.fetch({ 
     success: function() { 
     var view = new Blog.Views.PostsIndex({ collection: collection }); 
     console.log(collection); 
     } 
    }); 
    } 

}); 

回答

1

集合默認沒有標識。除非你明確地將一個ID分配給你的收藏,否則this.id變得未定義。 ID是模型的標準屬性。你想要做什麼簡單地說就是:

// Collection URL 
url: function() { 
    return '/api/posts' 
} 

骨幹機型,如果他們是一個集合的一部分獲取和保存時將使用收集url。因此,如果你做這樣的事情:

// myModel is a part of the collection 
myModel.save(); 

它會自動轉到:

'/api/posts/:id' // Assuming your model already has a model.id 

希望這有助於。

0

IMO你的代碼是錯誤的設計。您可以從here(請參閱blog/static/js/app.js)瞭解如何在骨幹上組織博客應用程序。