Samsun
Samsun

Reputation: 1

Singleton behaviour of javascript object

I want to have singleton kind of object whose value gets changed during multiple events across multiple pages. This object is used to bind the ui in various pages.

I have a 'main.js' file :

var obj = { flag : false } ;

 // call back method
 function click() { 
  obj.flag = true;
  }

and in my next.js file

 // call back method
  function click() { 
  alert(obj.flag); // **alerts false** . It should alert **true** instead.
  }

Is there a way to persist the value other than using the window.name property ? or am I following the wrong approach

Upvotes: 0

Views: 378

Answers (1)

Juna
Juna

Reputation: 338

You can use HTML5 localStorage. As described in the documentations (Safari, Mozilla etc.), localStorage supports string key/value pairs.

Therefore you need to use JSON.stringify to save your object in the storage.

var obj = { flag : false };

// Save the object in the storage
localStorage.setItem('obj', JSON.stringify(obj));

// Get the object from storage
var objectData = localStorage.getItem('obj');
var originalObject = JSON.parse(objectData );

alert(originalObject.flag);

See the following fiddle: http://jsfiddle.net/FdhzU/

Upvotes: 1

Related Questions