Backbone.js的收集选项 [英] Backbone.js collection options

查看:130
本文介绍了Backbone.js的收集选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Backbone.js的写了一个模型/视图/集合。我的收藏使用fetch方法从远程服务器加载模型。此集合所需的URL需要一个ID,如:邮件/ {ID}。但我发现没有干净的方式来传递选项集合。

该Backbone.js的视图通过将其建设接受选项:视图([选项]),但集合预计,在建设模式列表:集合([机型])

什么是传递参数/选项,这个集合的最干净的方式?

缩短code:

  VAR消息= Backbone.Collection.extend({
 型号:消息,
   网址:HTTP:// URL /消息/+ ID
});


解决方案

@保罗的回答是不错的,但它也是值得注意的是,网​​址属性可以是一个函数。在我看来,(它只是认为,既然最终的结果是一样的),在code是有点更清晰,如果更详细的,如果你设置中的id初始化,并在一个函数参考吧:

  VAR消息= Backbone.Collection.extend({
  初始化:功能(模型,期权){
    this.id = options.id;
  },
  网址:函数(){
    回报/消息/+ this.id;
  },
  型号:消息,
});VAR收集=新的消息([] {ID:2});
collection.fetch();

只是为了确保,虽然 - 你是不是混淆了 ID 在这里与模型 ID ,是您? @保罗的回答,我的code以上,假设你有多个的消息的集合,每个都有自己的ID。如果API路径 /消息/< ID> 实际上指的是一个的的消息的,而不是一组消息,那么你只需要设置网​​址 /消息/ 在收集和骨干将自动使用 /消息/&LT ;编号方式> 每个模型

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

解决方案

@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 in initialize and the reference it in a function:

var Messages = Backbone.Collection.extend({
  initialize: function(models, options) {
    this.id = options.id;
  },
  url: function() {
    return '/messages/' + this.id;
  },
  model: Message,
});

var collection = new Messages([], { id: 2 });
collection.fetch();

Just to make sure, though - you aren't confusing the id here with the Model id, are you? @Paul's answer, and my code above, assume that you have multiple Messages 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 the url to /messages/ in the Collection, and Backbone will automatically use /messages/<id> for each model.

这篇关于Backbone.js的收集选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆