Backbone.js 集合选项
我使用 Backbone.js 编写了模型/视图/集合。我的集合使用 fetch 方法从远程服务器加载模型。此集合所需的 url 需要一个 id,例如:messages/{id}。但我没有找到将选项传递给集合的干净方法。
Backbone.js 视图通过在构造时传递选项来接受选项:view([options]),但集合在构造时需要一个模型列表:collection([models])。
将参数/选项传递给该集合的“最干净”方式是什么?
缩短代码:
var Messages = Backbone.Collection.extend({
model: Message,
url: 'http://url/messages/' + id
});
I have written a model/view/collection using Backbone.js. My collection uses the fetch method to load the models from a remote server. The url required for this collection needs an id like: messages/{id}. But I have found no clean way to pass options to the Collection.
The backbone.js view accepts options by passing it on construction: view([options]), but the collection expects a list of models upon construction: collection([models]).
What is the "cleanest" way of passing parameters/options to this collection?
Shortened code:
var Messages = Backbone.Collection.extend({
model: Message,
url: 'http://url/messages/' + id
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Paul的答案很好,但值得注意的是
url
属性可以是一个函数。在我看来(这只是意见,因为最终结果是相同的),如果您在initialize
中设置 id 并在函数:只是为了确保 - 您没有将此处的
id
与模型id
混淆,是吗? @Paul 的回答和我上面的代码,假设您有多个Messages
集合,每个集合都有自己的 id。如果API路径/messages/
实际上引用的是一条消息,而不是一组消息,那么您只需设置url code> 到 Collection 中的
/messages/
,Backbone 会自动为每个模型使用/messages/
。@Paul's answer is good, but it's also worth noting that the
url
attribute can be a function. In my opinion (and it's just opinion, since the end result is the same), the code is a little more legible, if more verbose, if you set the id ininitialize
and the reference it in a function:Just to make sure, though - you aren't confusing the
id
here with the Modelid
, are you? @Paul's answer, and my code above, assume that you have multipleMessages
collections, each with its own id. If the API path/messages/<id>
actually refers to a message, not a set of messages, then you only need to set theurl
to/messages/
in the Collection, and Backbone will automatically use/messages/<id>
for each model.按照您声明 url 属性的方式,该值将在浏览器最初加载 javascript 文件时确定一次,并且“id”将是未定义的。
Backbone.Collection 接受选项作为其构造函数中的第二个参数,因此您可以将 id 值作为选项传递,然后在集合的初始化函数中设置 url 值。
这是一个例子
The way you have the url property declared, the value will be determined once when the browser initially loads the javascript file, and 'id' will be undefined.
The Backbone.Collection accepts options as the second argument in its constructor, so you can pass the id value as an option, and then set the url value within the initialize function of the collection.
Here's an example