Mobile Zone is brought to you in partnership with:

Jorge is the author of three software development books: "Building a Sencha Touch Application", "How to Build a jQuery Mobile Application", and the "Ext JS 3.0 Cookbook". He runs a software development and developer education shop that focuses on mobile, web and desktop technologies. Jorge is a DZone MVB and is not an employee of DZone and has posted 52 posts at DZone. You can read more from them at their website. View Full User Profile

Sencha Touch 2 Stores – Editing Model Instances and Reverting Changes

05.07.2013
| 6518 views |
  • submit to reddit
In this tutorial you are going to learn how to edit and save changes to the fields of a Sencha Touch Model instance, and under which conditions you can revert these changes. You will also learn how and when to query a Sencha Touch data store to obtain the records that have been updated.

The code that you will write in this tutorial is based on the application used in the Sencha Touch stores tutorial. This is a demo app that contains a Hotels Store loaded with instances of the Hotel model.

To start, you need to create the app’s directories:

st-stores-tut-1

And the index.html file, which should look like this:

sencha-touch-stores-example-3

Creating a Sencha Touch Model

You will create the Hotel.js file in the Model directory. In it, you will define the Hotel model:

Ext.define('App.model.Hotel', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            { name: 'id', type: 'int' },
            { name: 'name', type: 'string' },
            { name: 'address', type: 'string' },
            { name: 'status', type: 'int' }
        ]
    }
});

Defining a Sencha Touch Store

You will create the Hotels.js file in the Store directory. In the file, you will define the Hotels Store, and a few hard-coded model instances, as shown below:

Ext.define('App.store.Hotels', {
    extend: 'Ext.data.Store',
    config: {
        model: 'App.model.Hotel',
        data: [
            { id: 1, name: 'Siesta by the Ocean', address: '1 Ocean Front, Happy Island', status: 1 },
            { id: 2, name: 'Gulfwind', address: '25 Ocean Front, Happy Island', status: 0 },
            { id: 3, name: 'South Pole View', address: '1 Southernmost Point, Antarctica', status: 1 },
            { id: 4, name: 'North Pole View', address: '1 Northernmost Point, Artic Ocean', status: 0 }
        ],
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                rootProperty: 'hotels'
            }
        }
     }
});

In the Hotels store you are using a Memory proxy so you can save model instances without having to write server-side code.

Creating the Application

Now you can jump to the App directory and add the app.js file, where you will define a simple Sencha Touch application:

Ext.application({
    name: 'App',
    models: ['Hotel'],
    stores: ['Hotels'],
    launch: function () {

        var hotelsStore = Ext.getStore('Hotels');

    }
});

Editing the Fields of a Sencha Touch Model Instance

Let’s start the excercise by confirming that the hard-coded model instances exist in the Hotels store. You can do this executing a simple loop:

console.log('These are the hotels saved:');
hotelsStore.each(function (record) {
	console.log('- ' + record.get('name'));
});

Then, pick one of the model instances in the store, using the store’s getAt method:

var hotel = hotelsStore.getAt(1);
console.log("\nBEFORE UPDATE")
// Use a model's get method to get the value of a property.
console.log('The name of the second hotel is ' + hotel.get('name'));

You can edit any of the model’s fields using the set method. For example, you can change a hotel’s name like this:

hotel.set('name', 'Gulf Breeze');

console.log("\nAFTER UPDATE")
console.log('The updated name is ' + hotel.get('name'));

// Confirm that the store has the correct copy of the model instance.
console.log('These are the hotels after making changes:');
hotelsStore.each(function (record) {
	console.log('- ' + record.get('name'));
});

As you will see in a minute, the changes do not become permanent until you call the store’s sync method, or the model’s save method .

Retrieving Updated Records From a Sencha Touch Store

In your applications, you might need to find out which records in a store have been updated. You can retrieve the updates invoking a store’s getUpdatedRecords method:

// A store's getUpdatedRecords method gives you an array with the updated records.
var updatedRecords = hotelsStore.getUpdatedRecords();
console.log('These are the updated records:');
Ext.each(updatedRecords, function (record, index, length) {
	console.log('- ' + record.get('name'));
});

The call to getUpdatedRecords will return an array containing the model instances that have been updated since the last call to the store’s sync method. An important detail that many developers overlook is that if you call a store’s sync method and then call getUpdatedRecords, you will not retrieve the changes made prior to the call to sync. The same applies to calling getUpdatedRecords after calling a model’s save method.

How to Revert Changes to a Sencha Touch Model

You can also revert changes made to a model by invoking its reject method like so:

// Revert records to previous values.
hotel.reject();
console.log("\nAFTER REJECT")
console.log('Name of the hotel after rejecting changes: ' + hotel.get('name'));

// Confirm that the store has the correct copy of the model instance.
console.log('These are the hotels after rejecting changes:');
hotelsStore.each(function (record) {
	console.log('- ' + record.get('name'));
});

As when calling a store’ getUpdatedRecord method, if you call a model’s save method and then call reject, you will not revert the model back to the state prior to the save call. This also applies to calling revert on a model after calling sync on its store. You can see it happening in the following code:

hotel.set('name', 'Gulf Breeze');
hotelsStore.sync();
//hotel.save();       // You can call the store's sync method or the model's save method if the model has a proxy.
console.log("\nCHANGES COMMITTED")
hotel.reject();  // Will not revert the name back because you already called sync.
console.log("\nAFTER SAVE")
// Confirm that the store has the correct copy of the model instance.
console.log('These are the hotels after saving changes:');
hotelsStore.each(function (record) {
	console.log('- ' + record.get('name'));
});

Want To Learn More?

My Sencha Touch books will teach you how to create a Sencha Touch application, step by step, from mockups to production build.



Published at DZone with permission of Jorge Ramon, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)