BackboneJS:将更多项目加载到集合中
在 Backbone JS 中,当我获取集合时,我应该获取整个集合还是其中的一小部分?
例如,我在 mongoDB 中收集了新闻提要,其中可能有数千个项目。当用户点击页面时,我只想向他们展示最新的 10 项,并可以选择“加载更多”。但是,如果他们通过 URL http://site.com/#/feed/:itemID
访问特定项目,我希望能够提取该项目的记录。
1.我最初应该获取多少文档?
2.我如何通过 id 获取任何项目?
In Backbone JS when I fetch a collection should I be fetching the entire collection or a small portion of it?
For example I have news feed collection in mongoDB that could have potentially 1000s of items. When the user hits the page I only want to show them the latest 10 items with the option to 'Load More'. But if they visit a specific item via URL http://site.com/#/feed/:itemID
I want to be able to pull up that item's record.
1. How many document should I be fetching initially?
2. How would I got about fetching any item by id?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在对我的集合调用 fetch 时,我最终使用了
{add: true}
语句。这可以防止集合被获取的结果替换,而是将结果附加到集合中。然后,我还使用{data: {skip: amountOfItemsInCollectionAlready }
传递“跳过”金额,这在服务器端用于从数据库获取正确批次的项目。我的最终获取方法如下所示:
I ended up using the
{add: true}
statement when calling fetch on my collection. This prevents the collection from being replaced by the result of the fetch and but instead appends the result to the collection. I then also passed the 'skip' amount using the{data: {skip: amountOfItemsInCollectionAlready }
, this is used on the server-side to get the correct batch of items from the database.My final fetch method looks like this:
您可能不想只使用
Collection.fetch()
,因为您不会获得客户端缓存的好处 - 它会删除您已经从服务器加载的项目并重置集合。您可能需要使用自定义函数扩展Backbone.Collection
来检索更多项目。我在最近的项目中使用了以下代码:这主要是从默认的 fetch() 代码复制的,但它不会删除现有项目,而是添加新项目。您可能想在服务器端实现一些东西,使用
options
对象,因为Julien
建议传入您想要加载的项目的参数,可能是一个页面数字(如果您想在服务器上控制页面大小)或起止对(如果您想在客户端上控制它)。You probably don't want to just use
Collection.fetch()
, because you won't get the benefit of client-side caching - it'll drop the items you've already loaded from the server and reset the collection. You will probably need to extendBackbone.Collection
with a custom function to retrieve more items. I used the following code in a recent project:This is mostly copied from the default
fetch()
code, but instead of dropping existing items it will add new ones. You'd probably want to implement something server-side, using theoptions
object asJulien
suggests to pass in the parameters of what items you want to load, probably either a page number (if you want to control page size on the server) or a start-stop pair (if you want to control it on the client).1 - 您应该获取 10
将页面参数添加到您的集合中,并让后端代码返回匹配的页面(10/页)。 /my_objects?page=2 获取记录 10-20 等。
您可以这样做(未经测试):
或者直接更改 URL
2 - 要通过 ID 获取项目,您创建模型
并获取它
1 - You should be fetching 10
Add a page argument to your collection and have the backend code return the page matching (10/page). /my_objects?page=2 to get records 10-20 etc.
You do this like this (untested):
Or you alter the URL directly
2 - To fetch an item by ID you create the model
and fetch it