问题描述
我需要将一个 id 传递给一个集合以在 url 中使用(例如/user/1234/projects.json),但我不知道如何做到这一点,一个例子会很棒.
I need to pass an id to a collection for use in the url (e.g. /user/1234/projects.json) but am not sure how to do this, an example would be wonderful.
我的应用程序的结构方式是在启动时拉取并呈现用户"集合,然后我希望在单击用户时将他们的文档"从服务器拉入新集合并在新视图中呈现.问题是将用户 ID 放入文档集合中以提供文档的相关 URL.
The way my application is structured is on launch a collection of 'users' is pulled and rendered, I then want when a user is clicked their 'documents' are pulled from the server into a new collection and rendered in a new view. The issue is getting the user id into the documents collection to give the relevant URL for the documents.fetch().
我想我明白了,这是一个例子:
think I've got it, here is an example:
//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".
Your user collection url should be set to /user. Once that's set, your models should utilize that url in order to do their magic. I believe (not completely positive) that if a model is in a collection, calling the 'url' method will return /user/:id. So all your typical REST-ish functionality will be utilized on '/user/:id'. If you are trying to do something with a relationship (a user has many documents) it's kind of rinse and repeat. So, for your documents collection (which belogs to user correct?) you'd set the url to 'user_instance.url/documents'.
要显示与主干模型的一对多关系,您可以执行以下操作(将 urlRoot 升级到主干 0.5.1):
To show a one to many relationship with a backbone model, you'd do something like this (upgrade to backbone 0.5.1 for urlRoot):
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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论