[英]How can I get a collection of models from the server using Backbone.js?
I can't figure out the correct way to get a collection of models from the server into my Backbone Collection, assuming I don't want all the models from the DB, but rather a group of models (filtered by a specific model property). 假设我不希望数据库中的所有模型,而是一组模型(由特定模型属性过滤),则我无法找出从服务器将模型集合获取到我的Backbone集合中的正确方法。 。
The only way I can figure out is to override Fetch and use the function's "options" parameter to pass a filter definition to my Backbone.Sync function. 我能弄清楚的唯一方法是覆盖Fetch并使用函数的“ options”参数将过滤器定义传递给我的Backbone.Sync函数。
Is there a better way? 有没有更好的办法?
3 most used ways to set a collection, are 设置收藏集的3种最常用的方法是
bootstrapping models in the page, and then loading them with Collection.reset();
在页面中引导模型,然后使用
Collection.reset();
加载它们Collection.reset();
// you can print this trough serverside in your view, (you are bootstrapping these models) var bsModels = [{'name': 'name1'},{'name': 'name3'},{'name': 'name2'}]; // in your code you can use that bootstrapped data via the reset method. var myModel = Backbone.Model.extend({}); var myCollection = Backbone.Collection.extend({ model: myModel }); myCollection.reset(bsModels);
you can use the fetch, but it would load any and all methods, unless you override the fetch method 您可以使用fetch,但是它将加载所有方法,除非您覆盖fetch方法
a third option is to write your own ajax call, fetching the correct amount of models, and using the same technique as in #1, using Collection.reset(data);
第三种选择是编写自己的ajax调用,获取正确数量的模型,并使用与
Collection.reset(data);
相同的技术(与#1中相同Collection.reset(data);
Sure, there's a better way! 当然,有更好的方法! You can pass query params to your
fetch()
call. 您可以将查询参数传递给
fetch()
调用。 All of the options passed to fetch go straight into $.ajax()
. 传递给fetch的所有选项都直接进入
$.ajax()
。 So for example: 因此,例如:
myCollection.fetch({
data: {
search: "boo",
limit: "20"
}
}
Since this turns into a GET request, those will be appended to the query string, and you can parse them on the server and return the appropriate items for the collection. 由于这变成了GET请求,因此这些请求将被追加到查询字符串中,并且您可以在服务器上解析它们,并为集合返回适当的项目。
If you're feeling fancy, you can redefine fetch()
for a specific type of collection so that it always posts the appropriate query params. 如果您觉得花哨的话,可以为特定类型的集合重新定义
fetch()
,以便它始终发布适当的查询参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.