0

I want to store state of a simple application in a model, and be able to generate URL containing full state of the application (i.e., serialized model). Is there a backbone-idiomatic way to provide such a feature?

Related:

Community
  • 1
  • 1
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

1 Answers1

1

Backbone let's you serialize models to JSON but not to URL parameter syntax. You could stringify the JSON, url encode it, and then add it to the uRL ...

var json = yourModel.toJSON();
var jsonString = JSON.stringify(json);
var encoded = encodeURI(jsonString);
var url = 'www.example.com?model_json=' + jsonString;

... but I wouldn't recommend it. URL parameters were never designed to be used that way, and you can run in to lots of problems. One problem is character length limit. As this Stack Overflow answer explains, urls need to be limited to 2000 characters to be safe. Depending on what you put in your model, you could certainly exceed that without meaning to.

A much better approach would be to save the model somewhere that's designed to hold it, like on the server (that's exactly what the save method of a Backbone.Model is for, after all) or in local storage. Then, all you need to put in the URL is the model's ID, and you can use that ID to retrieve the data remotely/from local storage.

Community
  • 1
  • 1
machineghost
  • 33,529
  • 30
  • 159
  • 234