Reputation: 21536
I'm new to backbone and I thought one of the great things was that I could access the data without going back to the server. In the old version of my app, I was storing a hash of data in a dom node using jQuery.data.
So I have a list of messages, and when I click on a message, I want to go to a view which shows me more details, but all the details I need are already in the original list, so I don't actually need another run to the server, I just want to update the view.
Then when I want to go back to the list, again, I don't need to go back to the server, I just want to go back to the original list.
My routes look like this, and I tried to pass the 'messages' variable into the show function, but it isn't available to that function.
Am I misunderstanding the capabilities of backbone?
App.Routers.Messages = Backbone.Router.extend({ routes: { "": "index", "messages/:id": "show" }, show: function(id){ var message = new Message({ id: id}); message.fetch({ success: function(model, resp){ new App.Views.Show({ model: message}); }, error: function(){ new Error({message: "Hey!? Were'd it go? sorry I can't find your message"}); window.location.hash = '#'; } }); }, index: function(){ var messages = new App.Collections.Messages(); message.fetch({ success: function(){ new App.Views.Index(messages); }, error: function(){ new Error({ message: "did not find message :("}); } }); }
Upvotes: 2
Views: 455
Reputation: 4287
The problem is that the router works exactly like that: a route, once you click on the messages/:id view it reinitializes a new Messages model etc. If you move the fetch to the initialize method of your View and return that View as a so-called singleton (e.g. initialize it only once in your application), you won't need to do another server-call.
Upvotes: -1
Reputation: 18597
You can do what you desire with Backbone as well.
The only change you have to make is to set the collection of models to a global accessible variable.
So in the index function replace
var messages = new App.Collections.Messages();
with
App.messages = new App.Collections.Messages();
And then in your show function replace
var message = new Message({ id: id});
with
var message = App.messages.get(id);
Upvotes: 2