As suggested by Backbone documentation, I provide initial data for my collection when the html is rendered by my Rails app:
<script>
MyCollection.reset(<%= @items.to_json %>)
</script>
Now when an user trigger a specific Route, for example, she goes on #search/cats, i fetch the collection again, like this:
MyCollection.fetch({ data : { "query" : "cats" }})
The problem is that, when the user goes back, how do I reset the Collection again with the initial datas?
Don’t put that code in a block. It needs to be in a JavaScript file, in a method that you can call whenever you want to.
You still need to get the data rendered from your HTML file, though. To do this, you need to create an object that can have the data passed to it from the script block. Then you can store the data and use it later, when needed:
Your “myApp.js” file would contain the object definition with the “initialize” method:
Now whenever you need to, you can call
MyApp.resetCollectionand have it reset the collection with the data that you started with.Of course, there are dozens of ways to implement this. I’m only showing you the most basic version.