Working with models data.store and list in Sencha

Posted by | March 02, 2012 | JavaScript, Sencha | No Comments

There is no point in explaining what is MVC, if you don’t already know what is MVC well dear, then you got an issue … trust me I am an engineer :D. OK, now lets see how do we create our models in Sencha and fill the with information form back-end. I will create a models that holds the information related to user contact information. To keep this minimal the model could be something like:

 
**
 * Model mapping the contact details
 */
Ext.regModel('ContactDetails', {        
	//Contact website
	{
		name : 'website',
		type : 'string'
	},
	//Twitter account
	{
		name : 'twitter',
		type : 'string'
	}
        //TODO Add more  details :), I am lazy  
}
 
 
**
 * Model mapping the contact structure
 */
Ext.regModel('Contact', {
	//Contact name
	{
		name : 'name',
		type : 'string'
	},
	//Contact email
	{
		name : 'email',
		type : 'string'
	},
        //Contact details
        // Mapping Contact details model
	{
		name : 'detail',
		type : 'ContactDetails'
	},
 
}


OK now that we have created our model lets create our store that use the Contact model

 
var ContactStore = new Ext.data.Store({
        // mapping model
	model : 'Contact',
        // auto load with data from back-end
	autoLoad : true,
        // sort our contacts
	sortOnLoad : true,
	proxy : {		
		type : 'ajax',
		url : 'example.com/contacts.json/',		
	},
        //Add a custom sorting function by name
	sorters : [{
                //Set field used to sort the 
		property : 'name',		
		sorterFn : function(o1, o2) {
			var v1 = this.getRoot(o1)[this.property].toLowerCase(),
			 v2 = this.getRoot(o2)[this.property].toLowerCase();
 
			return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
		}
	}]
});

We did successfully created our store now lets put out data inside a list, this can be easily done by the following voodoo :

 
//Create the list of contacts
ContactsList = new Ext.List({
	id : 'contactslist',
	//Set data source
	store : ContactStore
});

This is it, now the model strong in you is Luke 🙂

About Andrei Tara

Andrei is a developer/geek who loves creating high quality and efficient applications, always following the best practices in software engineering. He loves the challenge of learning new, exciting things and playing with new languages, frameworks, and tools.

Leave a Reply