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

Backbone set collection attribute (for the url)

本文关键字:用于 url 属性 集合      更新时间:2023-09-26

我需要传递一个id到一个集合中使用的url(例如/user/1234/projects.json),但我不知道如何做到这一点,一个例子将是美妙的。

我的应用程序的结构方式是在启动时拉出并呈现"用户"集合,然后我希望当用户单击时,他们的"文档"从服务器拉出到一个新的集合中,并在一个新的视图中呈现。问题是如何将用户id获取到文档集合中,从而为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';
  }

您的用户集合url应该设置为/user。一旦设置好了,你的模型就应该利用这个url来施展它们的魔力。我相信(不是完全肯定),如果一个模型是在一个集合中,调用'url'方法将返回/user/:id。因此,所有典型的rest式功能都将在'/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') });

为什么需要用函数覆盖集合的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();

我喜欢Craig Monson的答案,但是为了让它工作,我需要修复两件事:

  • 在将User url方法传递给Docs之前绑定它
  • Docs
  • url函数的返回语句

更新的例子:

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