骨干集合集合属性(用于url)

时间:2011-07-18 14:51:10

标签: javascript backbone.js

我需要将一个id传递给一个集合以便在url中使用(例如/user/1234/projects.json),但我不知道如何做到这一点,一个例子会很精彩。

我的应用程序的结构方式是在启动时拉出并呈现“用户”的集合,然后我想在单击用户时将他们的“文档”从服务器拉到新集合中并在新视图中呈现。问题是将用户标识放入文档集合中,以提供documents.fetch()的相关URL。


我想我已经知道了,这是一个例子:

  //in the the view initialize function     
  this.collection = new Docs();
  this.collection.project_id = this.options.project_id;
  this.collection.fetch();

  //in the collection
  url: function() {
     return '/project/api/' +this.project_id+'/docs';
  }

3 个答案:

答案 0 :(得分:7)

您的用户集合网址应设置为/ user。一旦设置完毕,你的模型应该利用该网址来实现他们的魔力。我相信(并非完全正面)如果模型在集合中,调用'url'方法将返回/ user /:id。因此,所有典型的REST-ish功能都将用于'/ user /:id'。如果你试图用关系做某事(用户有很多文件),那就是冲洗和重复。那么,对于您的文档集合(这对用户来说是否正确?),您将URL设置为'user_instance.url / documents'。

要显示与骨干模型的一对多关系,您可以执行以下操作(针对urlRoot升级到主干0.5.1):

var User = Backbone.Model.extend({
    initialize: function() {
        // note, you are passing the function url.  This is important if you are
        // creating a new user that's not been sync'd to the server yet.  If you
        // did something like: {user_url: this.url()} it wouldn't contain the id
        // yet... and any sync through docs would fail... even if you sync'd the
        // user model!
        this.docs = new Docs([], {user_url: this.url});
    },
    urlRoot: '/user'
});

var Doc  = Backbone.Model.extend();

var Docs = Backbone.Collection.extend({
    initialize: function(models, args) {
        this.url = function() { args.user_url() + '/documents'; };
    }
});

var user = new User([{id: 1234}]);
user.docs.fetch({ success: function() { alert('win') });

答案 1 :(得分:5)

为什么需要用函数覆盖集合的URL属性?..你可以这样做:

 this.collection = new Docs();
 this.collection.project_id = this.options.project_id;
 this.collection.url = '/project/api/' + this.options.project_id + '/docs';
 this.collection.fetch();

答案 2 :(得分:0)

我喜欢Craig Monson的答案,但为了让它正常工作,我需要解决两件事:

  • 在将用户网址传递给文档
  • 之前对其进行绑定
  • 来自Docs
  • 中url函数的return语句

更新示例:

var User = Backbone.Model.extend({
    initialize: function() {
        // note, you are passing the function url.  This is important if you are
        // creating a new user that's not been sync'd to the server yet.  If you
        // did something like: {user_url: this.url()} it wouldn't contain the id
        // yet... and any sync through docs would fail... even if you sync'd the
        // user model!
        this.docs = new Docs([], { user_url: this.url.bind(this) });
        },
        urlRoot: '/user'
    });

var Doc  = Backbone.Model.extend();

var Docs = Backbone.Collection.extend({
    initialize: function(models, args) {
        this.url = function() { return args.user_url() + '/documents'; };
    }
});

var user = new User([{id: 1234}]);
user.docs.fetch({ success: function() { alert('win') });