铁轨和Backbone :: 何时渲染结果?
我正在使用 Backbone 和 Rails (3.1)。我有一个搜索页面。第一个搜索结果(显示分页的所有结果)应在页面加载时呈现。以后的搜索请求将使用主干。如何在不违反 DRY 的情况下做到这一点?
我可以在 Backbone 中执行所有请求,但是 (1) 这是页面加载上的又一个请求 (2) 主干喜欢在启动时设置集合。
来自主干文档:
加载引导模型 当您的应用程序首次加载时,通常会拥有一组您知道需要的初始模型,以便呈现页面。更好的模式是将数据引导到页面中,而不是触发额外的 AJAX 请求来获取它们。然后,您可以使用重置来使用初始数据填充您的集合。在 DocumentCloud,在工作区的 ERB 模板中,我们按照以下方式进行操作:
<script>
Accounts.reset(<%= @accounts.to_json %>);
Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>
I'm using Backbone with Rails (3.1). I have a search page. The first search results, displaying all results paginated, should be rendered when the page loads. later search requests will use backbone. How do I do this without violating DRY?
I could do all the requests in Backbone, but (1) that's one more request on the page load (2) backbone likes to have the collection set up on start up.
From backbone docs:
Loading Bootstrapped Models
When your app first loads, it's common to have a set of initial models that you know you're going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page. You can then use reset to populate your collections with the initial data. At DocumentCloud, in the ERB template for the workspace, we do something along these lines:
<script>
Accounts.reset(<%= @accounts.to_json %>);
Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以通过在Backbone中完成所有渲染,并让服务器只计算数据来做到这一点。
在第一次搜索时,您将搜索结果作为 JSON 包含在 Rails 视图中:
因此您初始化模型,并让 Backbone 渲染结果。 (您不会在 Rails 视图中呈现结果。)
在后续搜索中,您从 Rails 获取 JSON 结果并在 Backbone 中重置 search_results 集合,并且同一视图呈现结果。
You can do it by doing all the rendering in Backbone, and let the server only calculate the data.
On the first search, you include your search results as JSON in your Rails view:
So you initialize your model, and let Backbone do the rendering of the results. (You don't render the results in your Rails view.)
On subsequent searches, you get the JSON results from rails and reset your search_results collection in Backbone, and the same view renders the results.