Friday, 11 October 2013

Sencha Touch 2: How to extend model classes

Today, we are going to see how to extend from one model class to another model class in Sencha Touch 2. Sencha Touch follows object oriented methodology in which you can access the properties and method from one class to another class.

For Example, we will be having Contact class as our parent class with configuration fields  name, email, address etc . Following is the Contact Model Class implementation

Ext.define('MyApp.model.Contact', {
    extend: 'Ext.data.Model',

    config: {
        fields: [{
            name: 'firstName'
        }, {
            name: 'lastName'
        }, {
            name: 'email'
        }, {
            name: 'country'
        }, {
            name: 'state'
        }, {
            name: 'zipcode'
        }]
    }
});

Now, we will be creating a User model class by extending above created Contact model Class. So all the properties and methods from Contact Class will be available inside the User Class. Let's see the implementation

Ext.define('MyApp.model.User', {
    extend: 'MyApp.model.Contact',

    config: {
        fields: [{
            name: 'id'
        }, {
            name: 'usertype'
        },{
            name: 'active'
        }]
    }
});

Now, we are going to create an object instance for the User Model class with configuration properties which includes Contact Model Class. Here is the code

var user = Ext.create('MyApp.model.User',{
            id: 1,
            usertype: 'admin',
            active: 1,
            nameFirst: 'suresh',
            nameLast: 'kumar',
            email: 'youremail@domain.com',
            country: 'india',
            state: 'state',
            zipcode: 12345
});

Hope, you enjoyed this Post.

No comments:

Post a Comment