简体   繁体   English

如何在骨干.js中获取子视图/模型

[英]How to fetch sub views / models in backbone.js

Lets say you have a model "Blog" and a collection (and model) "Posts". 假设您有一个模型“博客”和一个集合(和模型)“帖子”。

How do you organize backbone code so that you can fetch the url "/blog/:blogID/posts" or "/posts?blog=:blogID" 如何组织主干代码,以便可以获取URL“ / blog /:blogID / posts”或“ / posts?blog =:blogID”

I am kinda confused on how to structure the code for this. 我对如何构造代码感到困惑。 Do you manually need to set the url when making a post list like: 在制作帖子列表时,您是否需要手动设置网址:

Blog = Backbone.Model.extend({
  initialize: function () {
    this.posts = new Posts({
      url: '/blogs/' + this.id + '/posts' }) } })

Or is there some better way to structure this? 还是有一些更好的方法来构造它?

That's how I would probably do it. 那就是我可能会这样做的方式。

Backbone doesn't really do much for you in the way of taking care of associations, so you have more manual work control when defining your models and how they relate (both in terms of the JavaScript and their URL representations). 骨干网在照顾关联方面并没有真正为您做很多事情,因此在定义模型以及模型之间的关系时(包括JavaScript及其URL表示),您可以进行更多的 手动工作 控制。

Once you define the URL on the collection, all of its contained models will work from that URL, so you really only have to deal with setting the URL when creating the collection. 在集合上定义URL后,所有包含的模型都可以从该URL使用,因此,您实际上只需要在创建集合时处理设置URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM