我需要将 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-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') });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)