Version: Smart Feature Phone 2.5

DataStore.onchange

The onchange event handler of the DataStore interface fires when a change is made to the data store. Its main use is to synchronize different apps that are using the data store when a change is made. When fired, this event returns a DataStoreChangeEvent, which can be used to handle the change that was just made. Alternatively, when the event fires you could create a DataStoreCursor and iterate through all the records, if needed.

Syntax#

store.onchange = function() {
// run some code to sync apps that use the data store
}

Example#

This section shows two approaches to handling the same problem — syncing data when another application makes a change to the data store.

In our first snippet, we retrieve all the data stores on the device with the name "contacts", then we use DataStore.sync to create a cursor to use for syncing the app with the current "content" data store (displaying new items, etc.) This cursor is passed to the runNextTask() function that will deal with running through the updates in some way. Next, we include some code inside an onchange function so that when a change is made we return the DataStoreChangeEvent, find out what type of task the change was, and then take action based on this type (either adding or deleting a contact's information.)

navigator.getDataStores('contacts').then(function(stores) {
var cursor = stores[0].sync();
runNextTask(cursor);
stores[0].onchange = function(e) {
if (e.operation == 'removed') {
// Delete the contact
deleteContact(e.id);
}
if (e.operation == 'added') {
stores[0].get(e.id).then(function(obj) {
// Add the new contact
loadData(obj,e.id);
});
}
}
});

In the second snippet, we retrieve all the data stores on the device with the name "contacts", then we use DataStore.sync to create a cursor to use for syncing the app with the current "content" data store (displaying new items, etc.) This cursor is passed to the runNextTask() function that will deal with running through the updates in some way. Next, we include the same code inside an onchange function , so that if a change is made to the data store by any app that uses it, the syncing process will be run again.

navigator.getDataStores('contacts').then(function(stores) {
var cursor = stores[0].sync();
runNextTask(cursor);
stores[0].onchange = function() {
contactList.innerHTML = '';
var cursor = stores[0].sync();
runNextTask(cursor);
}
});