Observable AbstractStore Store
Package: | Ext.data |
Defined In: | Store.js |
Class: | Store |
Subclasses: | ArrayStore, JsonPStore, JsonStore, XmlStore |
Extends: | AbstractStore |
The Store class encapsulates a client side cache of Model objects. Stores load data via a Proxy, and also provide functions for sorting, filtering and querying the model instances contained within it.
Creating a Store is easy - we just tell it the Model and the Proxy to use to load and save its data:
// Set up a model to use in our Store
Ext.regModel('User', {
fields: [
{name: 'firstName', type: 'string'},
{name: 'lastName', type: 'string'},
{name: 'age', type: 'int'},
{name: 'eyeColor', type: 'string'}
]
});
var myStore = new Ext.data.Store({
model: 'User',
proxy: {
type: 'ajax',
url : '/users.json',
reader: {
type: 'json',
root: 'users'
}
},
autoLoad: true
});
In the example above we configured an AJAX proxy to load data from the url '/users.json'. We told our Proxy to use a JsonReader to parse the response from the server into Model object - see the docs on JsonReader for details.
Inline data
Stores can also load data inline. Internally, Store converts each of the objects we pass in as data into Model instances:
new Ext.data.Store({
model: 'User',
data : [
{firstName: 'Ed', lastName: 'Spencer'},
{firstName: 'Tommy', lastName: 'Maintz'},
{firstName: 'Aaron', lastName: 'Conran'},
{firstName: 'Jamie', lastName: 'Avins'}
]
});
Loading inline data using the method above is great if the data is in the correct format already (e.g. it doesn't need to be processed by a reader). If your inline data requires processing to decode the data structure, use a MemoryProxy instead (see the MemoryProxy docs for an example).
Additional data can also be loaded locally using add.
Loading Nested Data
Applications often need to load sets of associated data - for example a CRM system might load a User and her Orders. Instead of issuing an AJAX request for the User and a series of additional AJAX requests for each Order, we can load a nested dataset and allow the Reader to automatically populate the associated models. Below is a brief example, see the Ext.data.Reader intro docs for a full explanation:
var store = new Ext.data.Store({
autoLoad: true,
model: "User",
proxy: {
type: 'ajax',
url : 'users.json',
reader: {
type: 'json',
root: 'users'
}
}
});
Which would consume a response like this:
{
"users": [
{
"id": 1,
"name": "Ed",
"orders": [
{
"id": 10,
"total": 10.76,
"status": "invoiced"
},
{
"id": 11,
"total": 13.45,
"status": "shipped"
}
]
}
]
}
See the Ext.data.Reader intro docs for a full explanation.
Filtering and Sorting
Stores can be sorted and filtered - in both cases either remotely or locally. The sorters and filters are held inside MixedCollection instances to make them easy to manage. Usually it is sufficient to either just specify sorters and filters in the Store configuration or call sort or filter:
var store = new Ext.data.Store({
model: 'User',
sorters: [
{
property : 'age',
direction: 'DESC'
},
{
property : 'firstName',
direction: 'ASC'
}
],
filters: [
{
property: 'firstName',
value : /Ed/
}
]
});
The new Store will keep the configured sorters and filters in the MixedCollection instances mentioned above. By default, sorting and filtering are both performed locally by the Store - see remoteSort and remoteFilter to allow the server to perform these operations instead.
Filtering and sorting after the Store has been instantiated is also easy. Calling filter adds another filter to the Store and automatically filters the dataset (calling filter with no arguments simply re-applies all existing filters). Note that by default sortOnFilter is set to true, which means that your sorters are automatically reapplied if using local sorting.
store.filter('eyeColor', 'Brown');
Change the sorting at any time by calling sort:
store.sort('height', 'ASC');
Note that all existing sorters will be removed in favor of the new sorter data (if sort is called with no arguments, the existing sorters are just reapplied instead of being removed). To keep existing filters and add new ones, just add sorters to the MixedCollection:
store.sorters.add(new Ext.util.Sorter({
property : 'shoeSize',
direction: 'ASC'
}));
store.sort();
Registering with StoreMgr
Any Store that is instantiated with a storeId will automatically be registed with the StoreMgr. This makes it easy to reuse the same store in multiple views:
//this store can be used several times
new Ext.data.Store({
model: 'User',
storeId: 'usersStore'
});
new Ext.List({
store: 'usersStore',
//other config goes here
});
new Ext.DataView({
store: 'usersStore',
//other config goes here
});
Further Reading
Stores are backed up by an ecosystem of classes that enables their operation. To gain a full understanding of these pieces and how they fit together, see:
Config Options | Defined By | |
---|---|---|
autoLoad : Boolean/Object If data is not specified, and if autoLoad is true or an Object, this store's load method
is automatically called afte... If data is not specified, and if autoLoad is true or an Object, this store's load method
is automatically called after creation. If the value of autoLoad is an Object, this Object will be passed to the store's
load method. Defaults to false. | AbstractStore | |
autoSave : Boolean True to automatically sync the Store with its Proxy after every edit to one of its Records.
Defaults to false. | AbstractStore | |
clearOnPageLoad : Boolean True to empty the store when loading another page via loadPage,
nextPage or previousPage (defaults to true). Setting... True to empty the store when loading another page via loadPage,
nextPage or previousPage (defaults to true). Setting to false keeps existing records, allowing
large data sets to be loaded one page at a time but rendered all together. | Store | |
data : Array Optional array of Model instances or data objects to load locally. See "Inline data" above for details. | Store | |
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 | |
proxy : String/Ext.data.Proxy/Object The Proxy to use for this Store. This can be either a string, a config
object or a Proxy instance - see setProxy for ... The Proxy to use for this Store. This can be either a string, a config
object or a Proxy instance - see setProxy for details. | Store | |
remoteFilter : Boolean True to defer any filtering operation to the server. If false, filtering is done locally on the client. Defaults to f... True to defer any filtering operation to the server. If false, filtering is done locally on the client. Defaults to false. | Store | |
remoteSort : Boolean True to defer any sorting operation to the server. If false, sorting is done locally on the client. Defaults to false... True to defer any sorting operation to the server. If false, sorting is done locally on the client. Defaults to false. | Store | |
sortOnFilter : Boolean | Store | |
storeId : String Optional unique identifier for this store. If present, this Store will be registered with
the Ext.StoreMgr, making i... Optional unique identifier for this store. If present, this Store will be registered with
the Ext.StoreMgr, making it easy to reuse elsewhere. Defaults to undefined. | AbstractStore |
Property | Defined By | |
---|---|---|
batchUpdateMode : String Sets the updating behavior based on batch synchronization. 'operation' (the default) will update the Store's
internal... Sets the updating behavior based on batch synchronization. 'operation' (the default) will update the Store's
internal representation of the data after each operation of the batch has completed, 'complete' will wait until
the entire batch has been completed before updating the Store's data. 'complete' is a good choice for local
storage proxies, 'operation' is better for remote proxies, where there is a comparatively high latency. | AbstractStore | |
currentPage : Number The page that the Store has most recently loaded (see loadPage) | Store | |
data : Ext.util.MixedCollection The MixedCollection that holds this store's local cache of records | Store | |
defaultProxyType : String The string type of the Proxy to create if none is specified. This defaults to creating a memory proxy. | AbstractStore | |
defaultSortDirection : String The default sort direction to use if one is not specified (defaults to "ASC") | AbstractStore | |
filterOnLoad : Boolean If true, any filters attached to this Store will be run after loading data, before the datachanged event is fired.
De... If true, any filters attached to this Store will be run after loading data, before the datachanged event is fired.
Defaults to true, ignored if remoteFilter is true | AbstractStore | |
filters : Ext.util.MixedCollection The collection of Filters currently applied to this Store | AbstractStore | |
groupDir : String The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DES... The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DESC" | Store | |
groupField : String The (optional) field by which to group data in the store. Internally, grouping is very similar to sorting - the
group... | Store | |
isDestroyed : Boolean True if the Store has already been destroyed via destroyStore. If this is true, the reference to Store should be dele... True if the Store has already been destroyed via destroyStore. If this is true, the reference to Store should be deleted
as it will not function correctly any more. | AbstractStore | |
pageSize : Number The number of records considered to form a 'page'. This is used to power the built-in
paging using the nextPage and p... The number of records considered to form a 'page'. This is used to power the built-in
paging using the nextPage and previousPage functions. Defaults to 25. | Store | |
snapshot : Ext.util.MixedCollection A pristine (unfiltered) collection of the records in this store. This is used to reinstate
records when a filter is r... A pristine (unfiltered) collection of the records in this store. This is used to reinstate
records when a filter is removed or changed | Store | |
sortOnLoad : Boolean If true, any sorters attached to this Store will be run after loading data, before the datachanged event is fired.
De... If true, any sorters attached to this Store will be run after loading data, before the datachanged event is fired.
Defaults to true, igored if remoteSort is true | AbstractStore | |
sortToggle : Object Stores the current sort direction ('ASC' or 'DESC') for each field. Used internally to manage the toggling
of sort di... Stores the current sort direction ('ASC' or 'DESC') for each field. Used internally to manage the toggling
of sort direction per field. Read only | AbstractStore | |
sorters : Ext.util.MixedCollection The collection of Sorters currently applied to this Store. | AbstractStore |
Method | Defined By | |
---|---|---|
Store( Object config )
Parameters:
| Store | |
add( Object data )
:
ArrayAdds Model instances to the Store by instantiating them based on a JavaScript object. When adding already-
instantiat... Adds Model instances to the Store by instantiating them based on a JavaScript object. When adding already-
instantiated Models, use insert instead. The instances will be added at the end of the existing collection.
This method accepts either a single argument array of Model instances or any number of model instance arguments.
Sample usage:
Parameters:
| Store | |
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 | |
clearFilter( Boolean suppressEvent )
:
voidRevert to a view of the Record cache with no filtering applied. Revert to a view of the Record cache with no filtering applied. Parameters:
| Store | |
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 | |
collect( String dataIndex , [Boolean allowNull ], [Boolean bypassFilter ] )
:
ArrayCollects unique values for a particular dataIndex from this store. Collects unique values for a particular dataIndex from this store. Parameters:
| Store | |
each( Function fn , [Object scope ] )
:
voidCalls the specified function for each of the Records in the cache. Calls the specified function for each of the Records in the cache. | Store | |
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 | |
filter( Mixed filters , String value )
:
voidFilters the loaded set of records by a given set of filters. Filters the loaded set of records by a given set of filters. Parameters:
| Store | |
filterBy( Function fn , [Object scope ] )
:
voidFilter by a function. The specified function will be called for each
Record in this Store. If the function returns tr... Filter by a function. The specified function will be called for each
Record in this Store. If the function returns true the Record is included,
otherwise it is filtered out. Parameters:
| Store | |
find( String fieldName , String/RegExp value , [Number startIndex ], [Boolean anyMatch ], [Boolean caseSensitive ], Boolean exactMatch )
:
NumberFinds the index of the first matching Record in this store by a specific field value. Finds the index of the first matching Record in this store by a specific field value. Parameters:
| Store | |
findBy( Function fn , [Object scope ], [Number startIndex ] )
:
NumberFind the index of the first matching Record in this Store by a function.
If the function returns true it is considere... Find the index of the first matching Record in this Store by a function.
If the function returns true it is considered a match. Parameters:
| Store | |
findExact( String fieldName , Mixed value , [Number startIndex ] )
:
NumberFinds the index of the first matching Record in this store by a specific field value. Finds the index of the first matching Record in this store by a specific field value. Parameters:
| Store | |
findRecord( String fieldName , String/RegExp value , [Number startIndex ], [Boolean anyMatch ], [Boolean caseSensitive ] )
:
Ext.data.RecordFinds the first matching Record in this store by a specific field value. Finds the first matching Record in this store by a specific field value. Parameters:
| Store | |
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 | |
first()
:
Ext.data.Model/undefined Convenience function for getting the first model instance in the store Convenience function for getting the first model instance in the store Parameters:
| Store | |
getAt( Number index )
:
Ext.data.ModelGet the Record at the specified index. Get the Record at the specified index. Parameters:
| Store | |
getById( String id )
:
Ext.data.RecordGet the Record with the specified id. Get the Record with the specified id. Parameters:
| Store | |
getCount()
:
Number Gets the number of cached records.
If using paging, this may not be the total size of the dataset. If the data object... Gets the number of cached records.
If using paging, this may not be the total size of the dataset. If the data object used by the Reader contains the dataset size, then the getTotalCount function returns the dataset size. Note: see the Important note in load. Parameters:
| Store | |
getGroupString( Ext.data.Model instance )
:
StringReturns the string to group on for a given model instance. The default implementation of this method returns the mode... Returns the string to group on for a given model instance. The default implementation of this method returns the model's
groupField, but this can be overridden to group by an arbitrary string. For example, to group by the first letter
of a model's 'name' field, use the following code:
Parameters:
| Store | |
getGroups()
:
Array Returns an object containing the result of applying grouping to the records in this store. See groupField,
groupDir a... Returns an object containing the result of applying grouping to the records in this store. See groupField,
groupDir and getGroupString. Example for a store containing records with a color field:
Parameters:
| Store | |
getNewRecords()
:
Array Returns all Model instances that are either currently a phantom (e.g. have no id), or have an ID but have not
yet bee... Returns all Model instances that are either currently a phantom (e.g. have no id), or have an ID but have not
yet been saved on this Store (this happens when adding a non-phantom record from another Store into this one) Parameters:
| AbstractStore | |
getProxy()
:
Ext.data.Proxy Returns the proxy currently attached to this proxy instance Returns the proxy currently attached to this proxy instance Parameters:
| AbstractStore | |
getRange( [Number startIndex ], [Number endIndex ] )
:
Ext.data.Model[]Returns a range of Records between specified indices. Returns a range of Records between specified indices. Parameters:
| Store | |
getSortState()
:
Object Returns an object describing the current sort state of this Store. Returns an object describing the current sort state of this Store. Parameters:
| AbstractStore | |
getUpdatedRecords()
:
Array Returns all Model instances that have been updated in the Store but not yet synchronized with the Proxy Returns all Model instances that have been updated in the Store but not yet synchronized with the Proxy Parameters:
| AbstractStore | |
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 | |
indexOf( Ext.data.Model record )
:
NumberGet the index within the cache of the passed Record. Get the index within the cache of the passed Record. Parameters:
| Store | |
indexOfId( String id )
:
NumberGet the index within the cache of the Record with the passed id. Get the index within the cache of the Record with the passed id. Parameters:
| Store | |
insert( Number index , Ext.data.Model[] records )
:
voidInserts Model instances into the Store at the given index and fires the add event.
See also add. | Store | |
isFiltered()
:
Boolean Returns true if this store is currently filtered Returns true if this store is currently filtered Parameters:
| Store | |
isLoading()
:
Boolean Returns true if the Store is currently performing a load operation Returns true if the Store is currently performing a load operation Parameters:
| Store | |
last()
:
Ext.data.Model/undefined Convenience function for getting the last model instance in the store Convenience function for getting the last model instance in the store Parameters:
| Store | |
load( Object/Function options )
:
voidLoads data into the Store via the configured proxy. This uses the Proxy to make an
asynchronous call to whatever stor... Loads data into the Store via the configured proxy. This uses the Proxy to make an asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved instances into the Store and calling an optional callback if required. Example usage:
If the callback scope does not need to be set, a function can simply be passed:
Parameters:
| Store | |
loadData( Array data , Boolean append )
:
voidLoads an array of data straight into the Store Loads an array of data straight into the Store Parameters:
| Store | |
loadPage( Number page )
:
voidLoads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a norma... Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal
load operation, passing in calculated 'start' and 'limit' params Parameters:
| Store | |
loadRecords( Array records , Boolean add )
:
voidLoads an array of {@Ext.data.Model model} instances into the store, fires the datachanged event. This should only usu... Loads an array of {@Ext.data.Model model} instances into the store, fires the datachanged event. This should only usually
be called internally when loading from the Proxy, when adding records manually use add instead Parameters:
| Store | |
nextPage()
:
void Loads the next 'page' in the current data set Loads the next 'page' in the current data set Parameters:
| Store | |
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 | |
previousPage()
:
void Loads the previous 'page' in the current data set Loads the previous 'page' in the current data set Parameters:
| Store | |
queryBy( Function fn , [Object scope ] )
:
MixedCollectionQuery the cached records in this Store using a filtering function. The specified function
will be called with each re... Query the cached records in this Store using a filtering function. The specified function
will be called with each record in this Store. If the function returns true the record is
included in the results. Parameters:
| Store | |
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 | |
remove( Ext.data.Model/Array records )
:
voidRemoves the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single
'... Removes the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single
'datachanged' event after removal. Parameters:
| Store | |
removeAt( Number index )
:
voidRemoves the model instance at the given index Removes the model instance at the given index Parameters:
| Store | |
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 | |
setProxy( String|Object|Ext.data.Proxy proxy )
:
Ext.data.ProxySets the Store's Proxy by string, config object or Proxy instance Sets the Store's Proxy by string, config object or Proxy instance Parameters:
| AbstractStore | |
sort( String|Array sorters , String direction )
:
voidSorts the data in the Store by one or more of its properties. Example usage:
//sort by a single field
myStore.sort('m... Sorts the data in the Store by one or more of its properties. Example usage:
Internally, Store converts the passed arguments into an array of Ext.util.Sorter instances, and delegates the actual sorting to its internal Ext.util.MixedCollection. When passing a single string argument to sort, Store maintains a ASC/DESC toggler per field, so this code:
Is equivalent to this code, because Store handles the toggling automatically:
Parameters:
| Store | |
sum( String property , [Number start ], [Number end ] )
:
NumberSums the value of property for each record between start
and end and returns the result. Sums the value of property for each record between start
and end and returns the result. Parameters:
| Store | |
suspendEvents( Boolean queueSuspended )
:
voidSuspend the firing of all events. (see resumeEvents) Suspend the firing of all events. (see resumeEvents) Parameters:
| Observable | |
sync()
:
void Synchronizes the Store with its Proxy. This asks the Proxy to batch together any new, updated
and deleted records in ... Synchronizes the Store with its Proxy. This asks the Proxy to batch together any new, updated
and deleted records in the store, updating the Store's internal representation of the records
as each operation completes. Parameters:
| AbstractStore | |
un( String eventName , Function handler , [Object scope ] )
:
voidRemoves an event handler (shorthand for removeListener.) Removes an event handler (shorthand for removeListener.) Parameters:
| Observable |
Event | Defined By | |
---|---|---|
add :
( Ext.data.Store store , Array records , Number index )
Fired when a Model instance has been added to this Store Fired when a Model instance has been added to this Store Listeners will be called with the following arguments:
| AbstractStore | |
beforeload :
( Ext.data.Store store , Ext.data.Operation operation )
Event description Event description Listeners will be called with the following arguments:
| AbstractStore | |
beforesync :
( Object options )
Called before a call to sync is executed. Return false from any listener to cancel the synv Called before a call to sync is executed. Return false from any listener to cancel the synv Listeners will be called with the following arguments:
| AbstractStore | |
datachanged :
( Ext.data.Store this )
Fires whenever the records in the Store have changed in some way - this could include adding or removing records,
or ... Fires whenever the records in the Store have changed in some way - this could include adding or removing records,
or updating the data in existing records Listeners will be called with the following arguments:
| AbstractStore | |
load :
( Ext.data.store this , Array records , Boolean successful )
Fires whenever the store reads data from a remote data source. Fires whenever the store reads data from a remote data source. Listeners will be called with the following arguments:
| AbstractStore | |
remove :
( Ext.data.Model record )
Fired when a Model instance has been removed from this Store Fired when a Model instance has been removed from this Store Listeners will be called with the following arguments:
| AbstractStore | |
update :
( Store this , Ext.data.Model record , String operation )
Fires when a Record has been updated Fires when a Record has been updated Listeners will be called with the following arguments:
| AbstractStore |