Version: Smart Feature Phone 2.5

DataStore

Description#

The DataStore interface of the Data Store API represents a retrieved set of data, and includes standard properties for accessing the store's name, owner, etc., methods for reading, modifying and syncing data, and the onchange event handler for reacting to changes to the data.

Properties#

Event handlers#

  • DataStore.onchange read-only Fired when a change is made to the data store, by any app that has permission to modify it.

Methods#

  • DataStore.get() Returns a specific record (or list of records) from the data store.
  • DataStore.add() Adds a new record to the data store; if the record you are attempting to add already exists, it will throw an exception.
  • DataStore.put() Updates an existing record in the data store.
  • DataStore.remove() Deletes a record (or list of records) from the data store
  • DataStore.clear() Deletes all records from the data store, leaving it empty.
  • DataStore.getLength() Returns the number of records currently in the data store.
  • DataStore.sync() Opens a cursor that allows you to step through any changes that have taken place in the data store going back to a particular revision ID, and run code in response to different types of change.

Example#

In the following example, we use navigator.getDataStores to return a list of DataStore objects representing data stores on the device called contacts. Since there is only one such data store, we can access it inside the outer promise using stores[0]. The next promise uses DataStore.getLength to return the number of records in the store. If the value is 0, we populate the data store with records contained in the contactsInit object; if there is already data in the store, we run DataStore.sync to loop through any additions since the code last accessed the data store and update the data display as necessary.

navigator.getDataStores('contacts').then(function(stores) {
stores[0].getLength().then(function(storeLength) {
if(storeLength == 0) {
for(i = 0; i < contactsInit.length; i++) {
addContact(stores[0],contactsInit[i]);
};
} else {
var cursor = stores[0].sync();
runNextTask(cursor);
}
});
});