2012-09-02 68 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)了解如何在骨干上组织博客应用程序。