Reputation: 15877
What would be the better path to take if I were in need of storing dynamically created content, which when inserted into the page, will have a pre-defined position within a container?
To make it a little more simpler to understand, say a user types something into an input box, which turns out to be a YouTube URL. Once he/she hits enter I take the URL and create an embedded video and add it to the page within a container of class name box
. This is the dynamic content.
This box can also be dragged using jQuery-ui, so the position will not always be the same. Now if I were to reload the page, I need the page to look exactly as it did before it reloaded, including the position and dynamically created content by the user.
I understand there are probably a number of ways to do such a thing, but there are limitations. Because there is no server available to store this information with, I am limited to using:
It's also worth mentioning that this will be used in a Google Chrome Extension.
So my question is, what would be the best way to store this kind of information given the limitations?
Example with what I'm working with here: http://fiddle.jshell.net/Shaz/pfs8a/30/show/light/
Upvotes: 0
Views: 398
Reputation: 169451
function contentHash(domNode) {
... // return unique id based on content / dom node.
}
var myUniqueSalt = ... // unique salt for your unique id's
window.localStorage.setItem(uniqueSalt + contentHash(domNode), "{'x':" + x + ",'y':" + y "}");
...
var position = JSON.parse(window.localStorage.getItem(uniqueSalt + contentHash(domNode));
object.x = position.x;
object.y = position.y;
Something along those lines should suffice.
You want a unique salt to ensure no-one overwrites your location in localStorage and then you want to get a unique id from your content that your storing the position.
Simply store the position as a JSON string then use JSON.parse to get your position object later.
of course check for whether the getItem returns an empty string and if so use the default.
I'll go even further to recommend you use backbone.js to store your data and connect it upto backbone.js-localstorage. Which overwrites the backbone.sync method so the models are saved locally.
This means you don't have to serialize your data into localstorage nor serialize it out of local storage.
Upvotes: 1