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>
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.