Mojo Storage Cookie

From WebOS Internals
Revision as of 06:20, 30 August 2009 by Rboatright (talk | contribs) (cookies)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Cookies are generally used to hold small amounts of information. A cookie may hold ONE OBJECT. That object can be any javascript object (we will see some options later) but the cookie can hold only one.

Typical uses for a cookie include User configuration for a game or other app, login info, etc.

When you want to use a cookie, the processes starts out the same no matter if you have already used a cookie or now.

You must set a variable to a cookie object. This is simple:

this.cookie = new Mojo.Model.Cookie('reversi');

the name inside the call to Mojo.Model.Cookie names a unique cookie that will be linked to YOUR APP.

If the cookie already exists, this.cookie is linked to it. If it does not exist, a new cookie is created.

this.cookie now has two important methods available. .get and .put

If you call .get, if the cookie exists, and has data in it, you get the object that was stored in the cookie returned to you. If the cookie does NOT have data in it, the .get returns undefined.

So, you can do:

cookieObject = this.cookie.get() if (cookieObject === undefined) {

    //do something that sets defaults

} else {

   //  do something with the data in cookieObject.

}

What can we store in a cookie? A cookie can store one object. You can store a string "abc". You can store a number 123, you can store the contents of a variable. That variable can contain an array which might have many values, but the VARIABLE is one object.

You can also store a javascript object. For example:

var myObject = {"name": "Fred", "Address": "123 w 4th St", "City": "Somewhere" }

now, we can store myObject in a cookie using the other call to the cookie we created earlier:

this.cookie.put(myObject)

stores myObject into the cookie.

Now, we can retrieve the object with

someOtherObect = this.cookie.get()

now, we can just refer to that object's properties...

someOtherObject.name will now be "Fred" someOtherObject.city will be Somewhere.

So, create an object. Get it. Check if it's undefined. If it is, define it. Otherwise, grab the data and go on. If the data changes, PUT IT BACK.

SImple