craftyjs.github.com

Storage

Utility to allow data to be saved to a permanent storage solution: IndexedDB, WebSql, localstorage or cookies

Back to top

.open

.open(String gameName)

gameName
a machine readable string to uniquely identify your game

Opens a connection to the database. If the best they have is localstorage or lower, it does nothing

Example

Open a database

Crafty.storage.open('MyGame');
Back to top

.save

.save(String key, String type, Mixed data)

key
A unique key for identifying this piece of data
type
'save' or 'cache'
data
Some kind of data.

Saves a piece of data to the database. Can be anything, although entities are preferred. For all storage methods but IndexedDB, the data will be serialized as a string During serialization, an entity's SaveData event will be triggered. Components should implement a SaveData handler and attach the necessary information to the passed object

Example

Saves an entity to the database

var ent = Crafty.e("2D, DOM")
                    .attr({x: 20, y: 20, w: 100, h:100});
Crafty.storage.open('MyGame');
Crafty.storage.save('MyEntity', 'save', ent);
Back to top

.load

.load(String key, String type)

key
A unique key to search for
type
'save' or 'cache'
callback
Do things with the data you get back

Loads a piece of data from the database. Entities will be reconstructed from the serialized string

Example

Loads an entity from the database

Crafty.storage.open('MyGame');
Crafty.storage.load('MyEntity', 'save', function (data) { // do things });
Back to top

.getAllKeys

.getAllKeys(String type)

type
'save' or 'cache'

Gets all the keys for a given type

Example

Gets all the save games saved

Crafty.storage.open('MyGame');
var saves = Crafty.storage.getAllKeys('save');
Back to top

.external

.external(String url)

url
URL to an external to save games too

Enables and sets the url for saving games to an external server

Example

Save an entity to an external server

Crafty.storage.external('http://somewhere.com/server.php');
Crafty.storage.open('MyGame');
var ent = Crafty.e('2D, DOM')
                    .attr({x: 20, y: 20, w: 100, h:100});
Crafty.storage.save('save01', 'save', ent);
Back to top

SaveData event

data
An object containing all of the data to be serialized
prepare
The function to prepare an entity for serialization

Any data a component wants to save when it's serialized should be added to this object. Straight attribute should be set in data.attr. Anything that requires a special handler should be set in a unique property.

Example

Saves the innerHTML of an entity

Crafty.e("2D DOM").bind("SaveData", function (data, prepare) {
    data.attr.x = this.x;
    data.attr.y = this.y;
    data.dom = this.element.innerHTML;
});