IT:AD:Sencha Touch:Concepts:Models
Summary
- Used to represent an object that a UI renders.
- Registered via the
Model Manager
- Used by
Stores
(which back Ext/Sencha data bound components) - All Models are specializations of
Ext.data.Model
* Models are made up of one or more of:name
fields
collectionvalidators
collectionproxy
*
fields
:- Item Attributes:
name
= …type
= auto|string|int|float|boolean|datedefaultValue
= …cool.convert
= pointer to method to wrap set… probably not so cool
validators
:- Item Attributes:
type
= presence|length|inclusion|exclusion|format (see References for more)field
= name of field being watched
- Examples:
- {type: 'presence', field: 'age'}
- {type: 'length', field: 'name', min: 2}
- {type: 'inclusion', field: 'gender', list: ['Male', 'Female']}
- {type: 'exclusion', field: 'username', list: ['Admin', 'Operator']}
- {type: 'format', field: 'username', matcher: /([a-z]+)[0-9]{2,3}/ }
proxy
:- Ext JS 4 concept of hooking a model up to datasource
- (active record?)
- several built in solutions:
RestProxy
Example (warning:Markdown munging):
Ext.define("User", { extend: "Ext.data.Model", fields: [ {name: 'id', type: 'int'}, {name: 'active', type: 'boolean', defaultValue:true } {name: 'first', type: 'string'}, {name: 'last', type: 'string'}, {name: 'dob', type: 'date'} ] someMethod : function() { return this.get('first') + ' ' this.get('last'); } someOtherMethod : function() { this.set('first') = this.set('first') + ' whatever'; } });
Creating Instances
Once defined, we can instantiate an instance of the model type:
var xModel = Ext.create( 'User', {id=1,first='John',last='Smith', dob='1999-12-20'} );
Validating Models
var instance = Ext.create('User', { name: 'Ed', gender: 'Male', username: 'edspencer' }); //A Ext.data.Errors is returned: var errors = instance.validate(); errors.isValid(); //false errors.length; //2 errors.items; //returns the array of all errors found on this model instance //ExtJS? errors.getByField('name'); // [{field: 'name', message: 'must be present'}] errors.getByField('title'); // [{field: 'title', message: 'is too short'}] //Sencha errors.forField('sku'); //returns the errors for the sku field