How to use localstorage in Titanium/Alloy?

Porwal picture Porwal · Jun 25, 2013 · Viewed 7k times · Source

I am very new to Appcelerator/Titanium. Can anyone tell me how to use localstorage function in Alloy (Titanium). (Not getting any good solution on Web).

Thanks! :)

Answer

felipecamposclarke picture felipecamposclarke · Jun 26, 2013

Titanium Alloy has a customized implemntación Backbone. This means that titanium uses Backbone for many things, but at the same time some important features have been left out.

One of the most used parts of Backbone by Titanium are models, while that not identical to those ofrese the js framework, they have lots of things in common.

To work with data models must define an adapter (this can be localStorage, sql, properties or custom sync adapters)

If you want to work with localStorage, your model should look something like this:

exports.definition = {

config: {
    "defaults": {
        "first_name": "",
        "last_name": "",
        "phone": "",
        "email": ""
    },
    "adapter": {
        "type": 'localStorage',
        "collection_name": 'user'
    }
},

extendModel: function(Model) {
    _.extend(Model.prototype, {
    }); // end extend

    return Model;
},

extendCollection: function(Collection) {
    _.extend(Collection.prototype, {
    }); // end extend

    return Collection;
}

};

to manipulate the data then you should use:

Create data

model = Alloy.createModel('user', {first_name: 'Pedro', last_name: Picapiedra});
// or model.save();
Alloy.Collections.user.add(model);

Read data

callection = Alloy.Collections.user.fetch()
model = Alloy.Collections.user.get(modelId)

Update data

user.set({
    first_name : 'Pablo',
    last_name : 'Marmol',
});

user.save();

Delete data

model.destroy();
collection.remove(model);

For more information:

Titanium Sync & apadters

Backbone Sync, collections, models & etc