通过id找到骨干集合

时间:2012-09-02 19:55:50

标签: backbone.js

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

});

2 个答案:

答案 0 :(得分:1)

默认情况下,集合没有ID。除非您明确为您的集合分配ID,否则this.id将变为未定义。 ID是模型的标准属性。你想做的只是:

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

Backbone模型,如果它们是集合的一部分,则在获取和保存时将使用集合url。因此,如果您这样做:

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

它将自动转到:

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

希望这有帮助。

答案 1 :(得分:0)

IMO您的代码设计错误。您可以从here(转到blog/static/js/app.js)了解如何在骨干网上组织博客应用。

相关问题