Observable Stateful Model
Package: | Ext.data |
Defined In: | Model.js |
Class: | Model |
Extends: | Stateful |
A Model represents some object that your application manages. For example, one might define a Model for Users, Products, Cars, or any other real-world object that we want to model in the system. Models are registered via the model manager, and are used by stores, which are in turn used by many of the data-bound components in Ext.
Models are defined as a set of fields and any arbitrary methods and properties relevant to the model. For example:
Ext.regModel('User', {
fields: [
{name: 'name', type: 'string'},
{name: 'age', type: 'int'},
{name: 'phone', type: 'string'},
{name: 'alive', type: 'boolean', defaultValue: true}
],
changeName: function() {
var oldName = this.get('name'),
newName = oldName + " The Barbarian";
this.set('name', newName);
}
});
The fields array is turned into a MixedCollection automatically by the ModelMgr, and all other functions and properties are copied to the new Model's prototype.
Now we can create instances of our User model and call any model logic we defined:
var user = Ext.ModelMgr.create({
name : 'Conan',
age : 24,
phone: '555-555-5555'
}, 'User');
user.changeName();
user.get('name'); //returns "Conan The Barbarian"
Validations
Models have built-in support for validations, which are executed against the validator functions in Ext.data.validations (see all validation functions). Validations are easy to add to models:
Ext.regModel('User', {
fields: [
{name: 'name', type: 'string'},
{name: 'age', type: 'int'},
{name: 'phone', type: 'string'},
{name: 'gender', type: 'string'},
{name: 'username', type: 'string'},
{name: 'alive', type: 'boolean', defaultValue: true}
],
validations: [
{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}/}
]
});
The validations can be run by simply calling the validate function, which returns a Ext.data.Errors object:
var instance = Ext.ModelMgr.create({
name: 'Ed',
gender: 'Male',
username: 'edspencer'
}, 'User');
var errors = instance.validate();
Associations
Models can have associations with other Models via belongsTo and hasMany associations. For example, let's say we're writing a blog administration application which deals with Users, Posts and Comments. We can express the relationships between these models like this:
Ext.regModel('Post', {
fields: ['id', 'user_id'],
belongsTo: 'User',
hasMany : {model: 'Comment', name: 'comments'}
});
Ext.regModel('Comment', {
fields: ['id', 'user_id', 'post_id'],
belongsTo: 'Post'
});
Ext.regModel('User', {
fields: ['id'],
hasMany: [
'Post',
{model: 'Comment', name: 'comments'}
]
});
See the docs for Ext.data.BelongsToAssociation and Ext.data.HasManyAssociation for details on the usage and configuration of associations. Note that associations can also be specified like this:
Ext.regModel('User', {
fields: ['id'],
associations: [
{type: 'hasMany', model: 'Post', name: 'posts'},
{type: 'hasMany', model: 'Comment', name: 'comments'}
]
});
Config Options | Defined By | |
---|---|---|
listeners : Object A config object containing one or more event handlers to be added to this
object during initialization. This should ... A config object containing one or more event handlers to be added to this object during initialization. This should be a valid listeners config object as specified in the addListener example for attaching multiple handlers at once. DOM events from ExtJs Components While some ExtJs Component classes export selected DOM events (e.g. "click", "mouseover" etc), this
is usually only done when extra value can be added. For example the DataView's
| Observable | |
persistanceProperty : String The property on this Persistable object that its data is saved to.
Defaults to 'data' (e.g. all persistable data resi... The property on this Persistable object that its data is saved to.
Defaults to 'data' (e.g. all persistable data resides in this.data.) | Stateful |
Property | Defined By | |
---|---|---|
dirty : Boolean Readonly flag - true if this Record has been modified. | Stateful | |
editing : Boolean Internal flag used to track whether or not the model instance is currently being edited. Read-only | Stateful | |
idProperty : String The name of the field treated as this Model's unique id (defaults to 'id'). | Model | |
modified : Object Key: value pairs of all fields whose values have changed | Stateful | |
phantom : Boolean true when the record does not yet exist in a server-side database (see
setDirty). Any record which has a real databa... true when the record does not yet exist in a server-side database (see
setDirty). Any record which has a real database pk set as its id property
is NOT a phantom -- it's real. | Model | |
store : Ext.data.Store The Ext.data.Store to which this Record belongs. | Model |
Method | Defined By | |
---|---|---|
Model( Object data , Number id )
Parameters:
| Model | |
Model.id( Record rec )
:
StringGenerates a sequential id. This method is typically called when a record is created
and no id has been specified. The... Generates a sequential id. This method is typically called when a record is created
and no id has been specified. The returned id takes the form:
{PREFIX}-{AUTO_ID}.
Parameters:
| Model | |
addEvents( Object|String o , string Optional. )
:
voidAdds the specified events to the list of events which this Observable may fire. Adds the specified events to the list of events which this Observable may fire. Parameters:
| Observable | |
addListener( String eventName , Function handler , [Object scope ], [Object options ] )
:
voidAppends an event handler to this object. Appends an event handler to this object. Parameters:
| Observable | |
addManagedListener( Observable|Element item , Object|String ename , Function fn , Object scope , Object opt )
:
voidAdds listeners to any Observable object (or Element) which are automatically removed when this Component
is destroyed... Adds listeners to any Observable object (or Element) which are automatically removed when this Component is destroyed. Parameters:
| Observable | |
clearListeners()
:
void Removes all listeners for this object including the managed listeners Removes all listeners for this object including the managed listeners Parameters:
| Observable | |
clearManagedListeners()
:
void Removes all managed listeners for this object. Removes all managed listeners for this object. Parameters:
| Observable | |
commit( [Boolean silent ] )
:
voidUsually called by the Ext.data.Store which owns the model instance.
Commits all changes made to the instance since ei... Usually called by the Ext.data.Store which owns the model instance.
Commits all changes made to the instance since either creation or the last commit operation.
Developers should subscribe to the Ext.data.Store.update event to have their code notified of commit operations. Parameters:
| Stateful | |
copy( [String id ] )
:
RecordCreates a copy (clone) of this Model instance. Creates a copy (clone) of this Model instance. Parameters:
| Stateful | |
enableBubble( String/Array events )
:
voidEnables events fired by this Observable to bubble up an owner hierarchy by calling
this.getBubbleTarget() if present.... Enables events fired by this Observable to bubble up an owner hierarchy by calling
This is commonly used by Ext.Components to bubble events to owner Containers. See Ext.Component.getBubbleTarget. The default implementation in Ext.Component returns the Component's immediate owner. But if a known target is required, this can be overridden to access the required target more quickly. Example:
Parameters:
| Observable | |
fireEvent( String eventName , Object... args )
:
BooleanFires the specified event with the passed parameters (minus the event name).
An event may be set to bubble up an Obse... Fires the specified event with the passed parameters (minus the event name). An event may be set to bubble up an Observable parent hierarchy (See Ext.Component.getBubbleTarget) by calling enableBubble. Parameters:
| Observable | |
get( String fieldName )
:
MixedReturns the value of the given field Returns the value of the given field Parameters:
| Stateful | |
getChanges()
:
Object Gets a hash of only the fields that have been modified since this Model was created or commited. Gets a hash of only the fields that have been modified since this Model was created or commited. Parameters:
| Stateful | |
getId()
:
Number Returns the unique ID allocated to this model instance as defined by idProperty Returns the unique ID allocated to this model instance as defined by idProperty Parameters:
| Model | |
getProxy()
:
Ext.data.Proxy Returns the configured Proxy for this Model Returns the configured Proxy for this Model Parameters:
| Model | |
hasListener( String eventName )
:
BooleanChecks to see if this object has any listeners for a specified event Checks to see if this object has any listeners for a specified event Parameters:
| Observable | |
isModified( String fieldName )
:
BooleanReturns true if the passed field name has been modified
since the load or last commit. Returns true if the passed field name has been modified
since the load or last commit.Parameters:
| Stateful | |
join( Ext.data.Store store )
:
voidTells this model instance that it has been added to a store Tells this model instance that it has been added to a store Parameters:
| Model | |
load( Number id , Object config )
:
voidAsynchronously loads a model instance by id. Sample usage:
MyApp.User = Ext.regModel('User', {
fields: [
... Asynchronously loads a model instance by id. Sample usage:
Parameters:
| Model | |
on( String eventName , Function handler , [Object scope ], [Object options ] )
:
voidAppends an event handler to this object (shorthand for addListener.) Appends an event handler to this object (shorthand for addListener.) Parameters:
| Observable | |
reject( [Boolean silent ] )
:
voidUsually called by the Ext.data.Store to which this model instance has been joined.
Rejects all changes made to the mo... Usually called by the Ext.data.Store to which this model instance has been joined.
Rejects all changes made to the model instance since either creation, or the last commit operation.
Modified fields are reverted to their original values.
Developers should subscribe to the Ext.data.Store.update event to have their code notified of reject operations. Parameters:
| Stateful | |
relayEvents( Object o , Array events )
:
voidRelays selected events from the specified Observable as if the events were fired by this. Relays selected events from the specified Observable as if the events were fired by this. Parameters:
| Observable | |
removeListener( String eventName , Function handler , [Object scope ] )
:
voidRemoves an event handler. Removes an event handler. Parameters:
| Observable | |
removeManagedListener( Observable|Element item , Object|String ename , Function fn , Object scope )
:
voidRemoves listeners that were added by the mon method. Removes listeners that were added by the mon method. Parameters:
| Observable | |
resumeEvents()
:
void Resume firing events. (see suspendEvents)
If events were suspended using the queueSuspended parameter, then all
event... Resume firing events. (see suspendEvents)
If events were suspended using the queueSuspended parameter, then all
events fired during event suspension will be sent to any listeners now. Parameters:
| Observable | |
save( Object options )
:
Ext.data.ModelSaves the model instance using the configured proxy Saves the model instance using the configured proxy Parameters:
| Model | |
set( String|Object fieldName , Mixed value )
:
voidSets the given field to the given value, marks the instance as dirty Sets the given field to the given value, marks the instance as dirty Parameters:
| Stateful | |
setDirty()
:
void Marks this Record as dirty. This method
is used interally when adding phantom records to a
writer enabled store.
Mar... Marks this Record as Marking a record Parameters:
| Stateful | |
setId( Number id )
:
voidSets the model instance's id field to the given id Sets the model instance's id field to the given id Parameters:
| Model | |
setProxy( String/Object/Ext.data.Proxy proxy )
:
voidSets the Proxy to use for this model. Accepts any options that can be accepted by Ext.data.ProxyMgr.create Sets the Proxy to use for this model. Accepts any options that can be accepted by Ext.data.ProxyMgr.create Parameters:
| Model | |
suspendEvents( Boolean queueSuspended )
:
voidSuspend the firing of all events. (see resumeEvents) Suspend the firing of all events. (see resumeEvents) Parameters:
| Observable | |
un( String eventName , Function handler , [Object scope ] )
:
voidRemoves an event handler (shorthand for removeListener.) Removes an event handler (shorthand for removeListener.) Parameters:
| Observable | |
unjoin( Ext.data.Store store )
:
voidTells this model instance that it has been removed from the store Tells this model instance that it has been removed from the store Parameters:
| Model | |
validate()
:
Ext.data.Errors Validates the current data against all of its configured validations and returns an
Errors object Validates the current data against all of its configured validations and returns an
Errors object Parameters:
| Model |