I have made a class in javascript with an object that contains both variables and functions. I instantiate the object within one .html page, but when I change to another .html page, the object seems to be 'empty'. How can I pass the object between one page to another?
-
3You can't really. Or more precisely : there is a better solution to your real problem.Denys Séguret– Denys Séguret2013-03-25 17:25:34 +00:00Commented Mar 25, 2013 at 17:25
-
Which framework are you using?Khanh Tran– Khanh Tran2013-03-25 17:26:49 +00:00Commented Mar 25, 2013 at 17:26
-
You might use AJAX to load page fragments using Javascript. You could keep the state of the Javascript on the main page and still load other pages.Waleed Khan– Waleed Khan2013-03-25 17:27:06 +00:00Commented Mar 25, 2013 at 17:27
-
You can't, state is lost when you switch pages. You could look into single-page applications (SPA) where you technically stay on the same page, but change the content on that page, or you need to maintain state on the server and use ajax or something to send the objects you want back every page.PherricOxide– PherricOxide2013-03-25 17:27:22 +00:00Commented Mar 25, 2013 at 17:27
-
@dystroy which one is that 'better solution' to my problem?Monica– Monica2013-03-25 18:00:45 +00:00Commented Mar 25, 2013 at 18:00
|
Show 1 more comment
2 Answers
You can have a look at Web Storage. This won't allow you to store a full JavaScript object, however you will be able to store as many string name-value pairs as you want. Either permanently (between browser restarts) or as part of a session.
1 Comment
Monica
Finally I used this to access the internal attributes of the object. The functions are still working because I've declared a global variable for the object.
Use localStorage, check this lib: https://github.com/marcuswestin/store.js
You can do something like:
store.set('foo', originalObject);
and then...
var restoredObject = store.get('foo');
Removing stored objects:
store.remove('foo');
Fork "jQuery-like" syntax: http://pastebin.com/x3KpKyr1
3 Comments
Monica
does this work with ALL objects? because I believe that this is only working with JSON objects that can be stringified...
neiker
Obviously this only works with objects that can be serialized... Objects with methods/functions can't. Why you would like to serialize behavior?
Monica
I guess because I'm really used to program in java... I've got methods that connect to the server to get information, and they're inside the object.