Class: SC.Store


Extends SC.Object.

The Store is where you can find all of your dataHashes. Stores can be chained for editing purposes and committed back one chain level at a time all the way back to a persistent data source.

Every application you create should generally have its own store objects. Once you create the store, you will rarely need to work with the store directly except to retrieve records and collections.

Internally, the store will keep track of changes to your json data hashes and manage syncing those changes with your data source. A data source may be a server, local storage, or any other persistent code.

Defined in: store.js.

Field Summary

Instance Methods

Field Detail

Error CHAIN_CONFLICT_ERROR

Standard error raised if you try to commit changes from a nested store and there is a conflict.

SC.Set changelog

A set of storeKeys that need to be committed back to the data source. If you call commitRecords() without passing any other parameters, the keys in this set will be committed instead.

childRecords
A hash of child Records and there immediate parents
Boolean commitRecordsAutomatically
This type of store is not nested.
Default Value:
NO
SC.DataSource dataSource

The data source is the persistent storage that will provide data to the store and save changes. You normally will set your data source when you first create your store in your application.

String EDITABLE
Data hash state indicates the data hash is currently editable
Array editables

Array indicates whether a data hash is possibly in use by an external record for editing. If a data hash is editable then it may be modified at any time and therefore chained stores may need to clone the attributes before keeping a copy of them.

Note that this is kept as an array because it will be stored as a dense array on some browsers, making it faster.

String INHERITED

Data hash state indicates the hash is tracking changes from the parent store and is not editable.

Boolean isNested
This type of store is not nested.
Default Value:
NO
String LOCKED

Data hash state indicates the hash no longer tracks changes from a parent store, but it is not editable.

String name

An (optional) name of the store, which can be useful during debugging, especially if you have multiple nested stores.

Error NESTED_STORE_RETRIEVE_DIRTY_ERROR

Standard error if you try to retrieve a record in a nested store that is dirty. (This is allowed on the main store, but not in nested stores.)

Error NESTED_STORE_UNSUPPORTED_ERROR

Standard error if you try to perform an operation on a nested store that is only supported in root stores.

Array nestedStores

An array of all the chained stores that current rely on the receiver store.

Error NO_PARENT_STORE_ERROR

Standard error if you try to perform an operation on a nested store without a parent.

parentRecords
A hash of parent records with registered children
Hash queryErrors

A hash of SC.Error objects associated with queries (indexed by the GUID of the query).

Errors passed from the data source in the call to dataSourceDidErrorQuery() are stored here.

Array recordErrors

An array of SC.Error objects associated with individual records in the store (indexed by store keys).

Errors passed form the data source in the call to dataSourceDidError() are stored here.

Instance Method Detail

cancelRecord

Cancels an inflight request for the passed record. Depending on the server implementation, this could cancel an entire request, causing other records to also transition their current state.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
ids to destroy
Array storeKeys
(optional) store keys to destroy
Returns:
SC.Store the store.
cancelRecords

Cancels an inflight request for the passed records. Depending on the server implementation, this could cancel an entire request, causing other records to also transition their current state.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
ids to destroy
Array storeKeys
(optional) store keys to destroy
Returns:
SC.Store the store.
cascade

Convenience method. Creates a CascadeDataSource with the passed data source arguments and sets the CascadeDataSource as the data source for the receiver.

Parameters:
SC.DataSource... dataSource
one or more data source arguments
Returns:
SC.Store receiver
chain

Returns a new nested store instance that can be used to buffer changes until you are ready to commit them. When you are ready to commit your changes, call commitChanges() or destroyChanges() and then destroy() when you are finished with the chained store altogether.

store = MyApp.store.chain();
.. edit edit edit
store.commitChanges().destroy();
Parameters:
Hash attrs
optional attributes to set on new store
Class newStoreClass
optional the class of the newly-created nested store (defaults to SC.NestedStore)
Returns:
SC.NestedStore new nested store chained to receiver
commitRecord

Commits the passed store key or id. Based on the current state of the record, this will ask the data source to perform the appropriate action on the store key.

You have to pass either the id or the storeKey otherwise it will return NO.

Parameters:
SC.Record recordType
the expected record type
String id
the id of the record to commit
Number storeKey
the storeKey of the record to commit
Hash params
optional additional params that will passed down to the data source
Function|Array callback
function or array of functions
Returns:
Boolean if the action was successful.
commitRecords

Commits the passed store keys or ids. If no storeKeys are given, it will commit any records in the changelog.

Based on the current state of the record, this will ask the data source to perform the appropriate actions on the store keys.

Parameters:
Array recordTypes
the expected record types (SC.Record)
Array ids
to commit
SC.Set storeKeys
to commit
Hash params
optional additional parameters to pass along to the data source
Function|Array callback
function or array of callbacks
Returns:
Boolean if the action was succesful.
createRecord

Creates a new record instance with the passed recordType and dataHash. You can also optionally specify an id or else it will be pulled from the data hash.

Note that the record will not yet be saved back to the server. To save a record to the server, call commitChanges() on the store.

Parameters:
SC.Record recordType
the record class to use on creation
Hash dataHash
the JSON attributes to assign to the hash.
String id
(optional) id to assign to record
Returns:
SC.Record Returns the created record
createRecords

Creates an array of new records. You must pass an array of dataHashes plus a recordType and, optionally, an array of ids. This will create an array of record instances with the same record type.

If you need to instead create a bunch of records with different data types you can instead pass an array of recordTypes, one for each data hash.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array dataHashes
array of data hashes
Array ids
(optional) ids to assign to records
Returns:
Array array of materialized record instances.
dataHashDidChange

Call this method whenever you modify some editable data hash to register with the Store that the attribute values have actually changed. This will do the book-keeping necessary to track the change across stores including managing locks.

Parameters:
Number|Array storeKeys
one or more store keys that changed
Number rev
optional new revision number. normally leave null
Boolean statusOnly
(optional) YES if only status changed
String key
that changed (optional)
Returns:
SC.Store receiver
dataSourceDidCancel

Called by a dataSource when it cancels an inflight operation on a record. This will transition the record back to it non-inflight state.

Parameters:
Number storeKey
record store key to cancel
Returns:
SC.Store receiver
dataSourceDidCancelQuery

Called by your data source if it cancels fetching the results of a query. This will put any RecordArray's back into its original state (READY or EMPTY).

Parameters:
SC.Query query
the query you cancelled
Returns:
SC.Store receiver
dataSourceDidComplete

Called by a data source when it creates or commits a record. Passing an optional id will remap the storeKey to the new record id. This is required when you commit a record that does not have an id yet.

Parameters:
Number storeKey
record store key to change to READY_CLEAN state
Hash dataHash
optional data hash to replace current hash
Object newId
optional new id to replace the old one
Returns:
SC.Store receiver
dataSourceDidDestroy

Called by a data source when it has destroyed a record. This will transition the record to the proper state.

Parameters:
Number storeKey
record store key to cancel
Returns:
SC.Store receiver
dataSourceDidError
Converts the passed record into an error object.
Parameters:
Number storeKey
record store key to error
SC.Error error
[optional] an SC.Error instance to associate with storeKey
Returns:
SC.Store receiver
dataSourceDidErrorQuery

Called by your data source if it encountered an error loading the query. This will put the query into an error state until you try to refresh it again.

Parameters:
SC.Query query
the query with the error
SC.Error error
[optional] an SC.Error instance to associate with query
Returns:
SC.Store receiver
dataSourceDidFetchQuery

Called by your data source whenever you finish fetching the results of a query. This will put the query into a READY state if it was loading.

Note that if the query is a REMOTE query, then you must separately load the results into the query using loadQueryResults(). If the query is LOCAL, then the query will update automatically with any new records you added to the store.

Parameters:
SC.Query query
the query you fetched
Returns:
SC.Store receiver
destroyRecord

Destroys a record, removing the data hash from the store and adding the record to the destroyed changelog. If you try to destroy a record that is already destroyed then this method will have no effect. If you destroy a record that does not exist or an error then an exception will be raised.

Parameters:
SC.Record recordType
the recordType
String id
the record id
Number storeKey
(optional) if passed, ignores recordType and id
Returns:
SC.Store receiver
destroyRecords

Destroys a group of records. If you have a set of record ids, destroying them this way can be faster than retrieving each record and destroying it individually.

You can pass either a single recordType or an array of recordTypes. If you pass a single recordType, then the record type will be used for each record. If you pass an array, then each id must have a matching record type in the array.

You can optionally pass an array of storeKeys instead of the recordType and ids. In this case the first two parameters will be ignored. This is usually only used by low-level internal methods. You will not usually destroy records this way.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
ids to destroy
Array storeKeys
(optional) store keys to destroy
Returns:
SC.Store receiver
find

Finds a single record instance with the specified recordType and id or an array of records matching some query conditions.

Finding a Single Record

If you pass a single recordType and id, this method will return an actual record instance. If the record has not been loaded into the store yet, this method will ask the data source to retrieve it. If no data source indicates that it can retrieve the record, then this method will return null.

Note that if the record needs to be retrieved from the server, then the record instance returned from this method will not have any data yet. Instead it will have a status of SC.Record.READY_LOADING. You can monitor the status property to be notified when the record data is available for you to use it.

Find a Collection of Records

If you pass only a record type or a query object, you can instead find all records matching a specified set of conditions. When you call find() in this way, it will create a query if needed and pass it to the data source to fetch the results.

If this is the first time you have fetched the query, then the store will automatically ask the data source to fetch any records related to it as well. Otherwise you can refresh the query results at anytime by calling refresh() on the returned RecordArray.

You can detect whether a RecordArray is fetching from the server by checking its status.

Examples

Finding a single record:

MyApp.store.find(MyApp.Contact, "23"); // returns MyApp.Contact

Finding all records of a particular type:

MyApp.store.find(MyApp.Contact); // returns SC.RecordArray of contacts

Finding all contacts with first name John:

var query = SC.Query.local(MyApp.Contact, "firstName = %@", "John");
MyApp.store.find(query); // returns SC.RecordArray of contacts

Finding all contacts using a remote query:

var query = SC.Query.remote(MyApp.Contact);
MyApp.store.find(query); // returns SC.RecordArray filled by server
Parameters:
SC.Record|String recordType
the expected record type
String id
the id to load
Returns:
SC.Record record instance or null
flush

Delivers any pending changes to materialized records. Normally this happens once, automatically, at the end of the RunLoop. If you have updated some records and need to update records immediately, however, you may call this manually.

Returns:
SC.Store receiver
from

Convenience method. Sets the current data source to the passed property. This will also set the store property on the dataSource to the receiver.

If you are using this from the core.js method of your app, you may need to just pass a string naming your data source class. If this is the case, then your data source will be instantiated the first time it is requested.

Parameters:
SC.DataSource|String dataSource
the data source
Returns:
SC.Store receiver
generateStoreKey
Generates a new store key for use.
hasNestedStore

Used to determine if a nested store belongs directly or indirectly to the receiver.

Parameters:
SC.Store store
store instance
Returns:
Boolean YES if belongs
idFor
Given a `storeKey`, return the `primaryKey`.
Parameters:
Number storeKey
the store key
Returns:
String primaryKey value
loadQueryResults

Sets the passed array of storeKeys as the new data for the query. You can call this at any time for a remote query to update its content. If you want to use incremental loading, then pass a SparseArray object.

If the query you pass is not a REMOTE query, then this method will raise an exception. This will also implicitly transition the query state to SC.Record.READY.

If you called loadRecords() before to load the actual content, you can call this method with the return value of that method to actually set the storeKeys on the result.

Parameters:
SC.Query query
the query you are loading. must be remote.
SC.Array storeKeys
array of store keys
Returns:
SC.Store receiver
loadRecord

Convenience method can be called by the store or other parts of your application to load a record into the store. This method will take a recordType and a data hashes and either add or update the record in the store.

The loaded records will be in an SC.Record.READY_CLEAN state, indicating they were loaded from the data source and do not need to be committed back before changing.

This method will check the state of the storeKey and call either pushRetrieve() or dataSourceDidComplete(). The standard state constraints for these methods apply here.

The return value will be the storeKey used for the push. This is often convenient to pass into loadQuery(), if you are fetching a remote query.

If you are upgrading from a pre SproutCore 1.0 application, this method is the closest to the old updateRecord().

Parameters:
SC.Record recordType
the record type
Array dataHash
to update
Array id
optional. if not passed lookup on the hash
Returns:
String store keys assigned to these id
loadRecords

Convenience method can be called by the store or other parts of your application to load records into the store. This method will take a recordType and an array of data hashes and either add or update the record in the store.

The loaded records will be in an SC.Record.READY_CLEAN state, indicating they were loaded from the data source and do not need to be committed back before changing.

This method will check the state of each storeKey and call either pushRetrieve() or dataSourceDidComplete(). The standard state constraints for these methods apply here.

The return value will be the storeKeys used for each push. This is often convenient to pass into loadQuery(), if you are fetching a remote query.

If you are upgrading from a pre SproutCore 1.0 application, this method is the closest to the old updateRecords().

Parameters:
SC.Record recordTypes
the record type or array of record types
Array dataHashes
array of data hashes to update
Array ids
optional array of ids. if not passed lookup on hashes
Returns:
Array store keys assigned to these ids
materializeParentRecord
materialize the parent when passing in a store key for the child
Parameters:
childStoreKey
materializeRecord

Given a storeKey, return a materialized record. You will not usually call this method yourself. Instead it will used by other methods when you find records by id or perform other searches.

If a recordType has been mapped to the storeKey, then a record instance will be returned even if the data hash has not been requested yet.

Each Store instance returns unique record instances for each storeKey.

Parameters:
Number storeKey
The storeKey for the dataHash.
Returns:
SC.Record Returns a record instance.
parentStoreKeyExists
function for retrieving a parent record key
Parameters:
Number storeKey
The store key of the parent
peekStatus

Reads the current status for the storeKey without actually locking the record. Usually you won't need to use this method. It is mostly used internally.

Parameters:
Number storeKey
the store key
Returns:
Number status
pushDestroy

Call by the data source whenever you want to push a deletion into the store.

Parameters:
Class recordType
the SC.Record subclass
Object id
the record id or null
Number storeKey
optional store key.
Returns:
Number|Boolean storeKey if push was allowed, NO if not
pushError

Call by the data source whenever you want to push an error into the store.

Parameters:
Class recordType
the SC.Record subclass
Object id
the record id or null
SC.Error error
[optional] an SC.Error instance to associate with id or storeKey
Number storeKey
optional store key.
Returns:
Number|Boolean storeKey if push was allowed, NO if not
pushRetrieve

Call by the data source whenever you want to push new data out of band into the store.

Parameters:
Class recordType
the SC.Record subclass
Object id
the record id or null
Hash dataHash
data hash to load
Number storeKey
optional store key.
Returns:
Number|Boolean storeKey if push was allowed, NO if not
queryFor

Given a storeKey, returns the query object associated with the key. If no query is associated with the storeKey, returns null.

Parameters:
Number storeKey
the store key
Returns:
SC.Query query query object
readDataHash

Returns the data hash for the given storeKey. This will also 'lock' the hash so that further edits to the parent store will no longer be reflected in this store until you reset.

Parameters:
Number storeKey
key to retrieve
Returns:
Hash data hash or null
readEditableDataHash

Returns the data hash for the storeKey, cloned so that you can edit the contents of the attributes if you like. This will do the extra work to make sure that you only clone the attributes one time.

If you use this method to modify data hash, be sure to call dataHashDidChange() when you make edits to record the change.

Parameters:
Number storeKey
the store key to retrieve
Returns:
Hash the attributes hash
readEditableProperty

Reads a property from the hash - cloning it if needed so you can modify it independently of any parent store. This method is really only well tested for use with toMany relationships. Although it is public you generally should not call it directly.

Parameters:
Number storeKey
storeKey of data hash
String propertyName
property to read
Returns:
Object editable property value
readError
Returns the `SC.Error` object associated with a specific record.
Parameters:
Number storeKey
The store key of the record.
Returns:
SC.Error SC.Error or undefined if no error associated with the record.
readQueryError
Returns the `SC.Error` object associated with a specific query.
Parameters:
SC.Query query
The SC.Query with which the error is associated.
Returns:
SC.Error SC.Error or undefined if no error associated with the query.
readStatus

Reads the current status for a storeKey. This will also lock the data hash. If no status is found, returns SC.RECORD_EMPTY.

Parameters:
Number storeKey
the store key
Returns:
Number status
recordArrayWillDestroy

Called by the record array just before it is destroyed. This will de-register it from receiving future notifications.

You should never call this method yourself. Instead call destroy() on the RecordArray directly.

Parameters:
SC.RecordArray recordArray
the record array
Returns:
SC.Store receiver
recordDidChange

Notes that the data for the given record id has changed. The record will be committed to the server the next time you commit the root store. Only call this method on a record in a READY state of some type.

Parameters:
SC.Record recordType
the recordType
String id
the record id
Number storeKey
(optional) if passed, ignores recordType and id
String key
that changed (optional)
Boolean if
the change is to statusOnly (optional)
Returns:
SC.Store receiver
recordsDidChange

Mark a group of records as dirty. The records will be committed to the server the next time you commit changes on the root store. If you have a set of record ids, marking them dirty this way can be faster than retrieving each record and destroying it individually.

You can pass either a single recordType or an array of recordTypes. If you pass a single recordType, then the record type will be used for each record. If you pass an array, then each id must have a matching record type in the array.

You can optionally pass an array of storeKeys instead of the recordType and ids. In this case the first two parameters will be ignored. This is usually only used by low-level internal methods.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
ids to destroy
Array storeKeys
(optional) store keys to destroy
Returns:
SC.Store receiver
recordsFor

Array of all records currently in the store with the specified type. This method only reflects the actual records loaded into memory and therefore is not usually needed at runtime. However you will often use this method for testing.

Parameters:
SC.Record recordType
the record type
Returns:
SC.Array array instance - usually SC.RecordArray
recordTypeFor
Given a storeKey, return the recordType.
Parameters:
Number storeKey
the store key
Returns:
SC.Record record instance
refreshQuery

Called by the record array whenever it needs the data source to refresh its contents. Nested stores will actually just pass this along to the parent store. The parent store will call fetch() on the data source.

You should never call this method yourself. Instead call refresh() on the RecordArray directly.

Parameters:
SC.Query query
the record array query to refresh
Returns:
SC.Store receiver
refreshRecord

Refreshes a record from the server. If the record has already been loaded in the store, then this method will request a refresh from the dataSource. Otherwise it will attempt to retrieve the record.

Parameters:
SC.Record recordType
the expected record type
String id
to id of the record to load
Number storeKey
(optional) optional store key
Function callback
(optional) when refresh completes
Returns:
Boolean YES if the retrieval was a success.
refreshRecords

Refreshes a set of records from the server. If the records has already been loaded in the store, then this method will request a refresh from the dataSource. Otherwise it will attempt to retrieve them.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
ids to destroy
Array storeKeys
(optional) store keys to destroy
Function callback
(optional) when refresh completes
Returns:
Boolean YES if the retrieval was a success.
registerChildToParent
register a Child Record to the parent
Parameters:
parentStoreKey
childStoreKey
path
removeDataHash

Removes the data hash from the store. This does not imply a deletion of the record. You could be simply unloading the record. Either way, removing the dataHash will be synced back to the parent store but not to the server.

Note that you can optionally pass a new status to go along with this. If you do not pass a status, it will change the status to SC.RECORD_EMPTY (assuming you just unloaded the record). If you are deleting the record you may set it to SC.Record.DESTROYED_CLEAN.

Be sure to also call dataHashDidChange() to register this change.

Parameters:
Number storeKey
String status
optional new status
Returns:
SC.Store receiver
replaceIdFor

Swaps the primaryKey mapped to the given storeKey with the new primaryKey. If the storeKey is not currently associated with a record this will raise an exception.

Parameters:
Number storeKey
the existing store key
String newPrimaryKey
the new primary key
Returns:
SC.Store receiver
replaceRecordTypeFor

Swaps the recordType recorded for a given storeKey. Normally you should not call this method directly as it can damage the store behavior. This method is used by other store methods to set the recordType for a storeKey.

Parameters:
Integer storeKey
the store key
SC.Record recordType
a record class
Returns:
SC.Store receiver
reset

Resets the store content. This will clear all internal data for all records, resetting them to an EMPTY state. You generally do not want to call this method yourself, though you may override it.

Returns:
SC.Store receiver
retrieveRecord

Retrieves a record from the server. If the record has already been loaded in the store, then this method will simply return. Otherwise if your store has a dataSource, this will call the dataSource to retrieve the record. Generally you will not need to call this method yourself. Instead you can just use find().

This will not actually create a record instance but it will initiate a load of the record from the server. You can subsequently get a record instance itself using materializeRecord().

Parameters:
SC.Record recordType
class
String id
id to retrieve
Number storeKey
(optional) store key
Boolean isRefresh
Function callback
(optional)
Returns:
Number storeKey that was retrieved
retrieveRecords

Retrieves a set of records from the server. If the records has already been loaded in the store, then this method will simply return. Otherwise if your store has a dataSource, this will call the dataSource to retrieve the record. Generally you will not need to call this method yourself. Instead you can just use find().

This will not actually create a record instance but it will initiate a load of the record from the server. You can subsequently get a record instance itself using materializeRecord().

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
ids to retrieve
Array storeKeys
(optional) store keys to retrieve
Boolean isRefresh
Function|Array callback
function or array of functions
Returns:
Array storeKeys to be retrieved
statusString
Returns string representation of a `storeKey`, with status.
Parameters:
Number storeKey
Returns:
String
storeKeyEditState

Returns the current edit status of a storekey. May be one of EDITABLE or LOCKED. Used mostly for unit testing.

Parameters:
Number storeKey
the store key
Returns:
Number edit status
storeKeyExists

Given a primaryKey value for the record, returns the associated storeKey. As opposed to storeKeyFor() however, this method will NOT generate a new storeKey but returned undefined.

Parameters:
SC.Record recordType
the record type
String primaryKey
the primary key
Returns:
Number a storeKey.
storeKeyFor

Given a recordType and primaryKey, find the storeKey. If the primaryKey has not been assigned a storeKey yet, it will be added.

Parameters:
SC.Record recordType
the record type
String primaryKey
the primary key
Returns:
Number storeKey
storeKeys

Finds all storeKeys in this store and returns an array.

Returns:
Array set of storeKeys
storeKeysFor

Finds all storeKeys of a certain record type in this store and returns an array.

Parameters:
SC.Record recordType
Returns:
Array set of storeKeys
toString
unloadRecord

Unloads a record, removing the data hash from the store. If you try to unload a record that is already destroyed then this method will have no effect. If you unload a record that does not exist or an error then an exception will be raised.

Parameters:
SC.Record recordType
the recordType
String id
the record id
Number storeKey
(optional) if passed, ignores recordType and id
newStatus
Returns:
SC.Store receiver
unloadRecords

Unloads a group of records. If you have a set of record ids, unloading them this way can be faster than retrieving each record and unloading it individually.

You can pass either a single recordType or an array of recordTypes. If you pass a single recordType, then the record type will be used for each record. If you pass an array, then each id must have a matching record type in the array.

You can optionally pass an array of storeKeys instead of the recordType and ids. In this case the first two parameters will be ignored. This is usually only used by low-level internal methods. You will not usually unload records this way.

Parameters:
SC.Record|Array recordTypes
class or array of classes
Array ids
(optional) ids to unload
Array storeKeys
(optional) store keys to unload
newStatus
Returns:
SC.Store receiver
writeDataHash

Replaces the data hash for the storeKey. This will lock the data hash and mark them as cloned. This will also call dataHashDidChange() for you.

Note that the hash you set here must be a different object from the original data hash. Once you make a change here, you must also call dataHashDidChange() to register the changes.

If the data hash does not yet exist in the store, this method will add it. Pass the optional status to edit the status as well.

Parameters:
Number storeKey
the store key to write
Hash hash
the new hash
String status
the new hash status
Returns:
SC.Store receiver
writeStatus

Writes the current status for a storeKey. If the new status is SC.Record.ERROR, you may also pass an optional error object. Otherwise this param is ignored.

Parameters:
Number storeKey
the store key
String newStatus
the new status
SC.Error error
optional error object
Returns:
SC.Store receiver
Documentation generated by JsDoc Toolkit 2.4.0 on Sat May 12 2012 15:15:06 GMT-0600 (CST)