OsfAdapter Class
Base adapter class for all OSF APIv2 endpoints
Item Index
Methods
- _addRelated
- _ajaxRequest
- _buildRelationshipURL
- _buildURL
- _createRelated
- _deleteRelated
- _doRelatedRequest
- _handleRelatedRequest
- _lazyInjections
- _makeRequest
- _onLookup
- _removeRelated
- _requestFor
- _requestToJQueryAjaxHash
- _scheduledDestroy
- _updateRelated
- addObserver
- ajax
- ajaxOptions
- beginPropertyChanges
- buildQuery
- buildURL
- cacheFor
- createRecord
- dataForRequest
- decrementProperty
- deleteRecord
- destroy
- endPropertyChanges
- findAll
- findBelongsTo
- findHasMany
- findMany
- findRecord
- generatedDetailedMessage
- generateIdForRecord
- get
- getProperties
- getWithDefault
- groupRecordsForFindMany
- handleResponse
- hasObserverFor
- headersForRequest
- incrementProperty
- init
- isInvalid
- isSuccess
- methodForRequest
- normalizeErrorResponse
- notifyPropertyChange
- parseErrorResponse
- pathForType
- propertyDidChange
- propertyWillChange
- query
- queryRecord
- removeObserver
- reopen
- reopenClass
- serialize
- set
- setProperties
- shouldBackgroundReloadAll
- shouldBackgroundReloadRecord
- shouldReloadAll
- shouldReloadRecord
- sortQueryParams
- toggleProperty
- toString
- updateRecord
- urlForCreateRecord
- urlForDeleteRecord
- urlForFindAll
- urlForFindBelongsTo
- urlForFindHasMany
- urlForFindMany
- urlForFindRecord
- urlForQuery
- urlForQueryRecord
- urlForRequest
- urlForUpdateRecord
- urlPrefix
- willDestroy
Methods
_addRelated
-
store
-
snapshot
-
addedSnapshots
-
relationship
-
url
-
isBulk
Handle add(s) of related resources. This differs from CREATEs in that the related record is already saved and is just being associated with the inverse record.
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshotsnapshot of inverse record
-
addedSnapshots
DS.Snapshot[] -
relationship
String -
url
String -
isBulk
Boolean
_ajaxRequest
-
options
Parameters:
-
options
ObjectjQuery ajax options to be used for the ajax request
_buildRelationshipURL
-
snapshot
-
relationship
Construct a URL for a relationship create/update/delete.
Parameters:
-
snapshot
DS.Snapshot -
relationship
Stringthe relationship to build a url for
Returns:
a URL
_createRelated
-
store
-
snapshot
-
createdSnapshots
-
relationship
-
url
-
isBulk
Handle creation of related resources
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshotsnapshot of inverse record
-
createdSnapshots
DS.Snapshot[] -
relationship
String -
url
String -
isBulk
Boolean
_deleteRelated
-
store
-
snapshot
-
deletedSnapshots
-
relationship
-
url
-
isBulk
Handle deletion of related resources
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshotsnapshot of inverse record
-
deletedSnapshots
DS.Snapshot[] -
relationship
String -
url
String -
isBulk
Boolean
_doRelatedRequest
-
store
-
snapshot
-
relatedSnapshots
-
relationship
-
url
-
requestMethod
-
isBulk
A helper for making _*Related requests
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshotsnapshot of inverse record
-
relatedSnapshots
DS.Snapshot[] -
relationship
String -
url
String -
requestMethod
String -
isBulk
Boolean
_handleRelatedRequest
-
store
-
type
-
snapshot
-
relationship
-
change
Delegate a series of requests based on a snapshot, relationship, and a change. The change argument can be 'delete', 'remove', 'update', 'add', 'create'
Parameters:
-
store
DS.Store -
type
DS.Model -
snapshot
DS.Snapshot -
relationship
String -
change
String
_lazyInjections
()
Object
private
Returns:
_makeRequest
-
request
jQuery.ajax
.
Parameters:
-
request
Object
Returns:
_onLookup
()
private
_removeRelated
-
store
-
snapshot
-
removedSnapshots
-
relationship
-
url
-
isBulk
Handle removal of related resources. This differs from DELETEs in that the related record is not deleted, just dissociated from the inverse record.
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshotsnapshot of inverse record
-
removedSnapshots
DS.Snapshot[] -
relationship
String -
url
String -
isBulk
Boolean
_requestFor
-
params
Parameters:
-
params
Object
Returns:
_requestToJQueryAjaxHash
-
request
jQuery.ajax
.
Parameters:
-
request
Object
Returns:
_scheduledDestroy
()
private
destroy
method.
_updateRelated
-
store
-
snapshot
-
updatedSnapshots
-
relationship
-
url
-
isBulk
Handle update(s) of related resources
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshotsnapshot of inverse record
-
updatedSnapshots
DS.Snapshot[] -
relationship
String -
url
String -
isBulk
Boolean
addObserver
-
key
-
target
-
method
context
parameter:
`
javascript
fooDidChange: function(sender, key, value, rev) { };
`
The sender is the object that changed. The key is the property that
changes. The value property is currently reserved and unused. The rev
is the last property revision of the object when it changed, which you can
use to detect if the key value has really changed or not.
If you pass a context
parameter, the context will be passed before the
revision like so:
`
javascript
fooDidChange: function(sender, key, value, context, rev) { };
`
Usually you will not need the value, context or revision parameters at
the end. In this case, it is common to write observer methods that take
only a sender and key value as parameters or, if you aren't interested in
any of these values, to write an observer that has no parameters at all.
ajax
-
url
-
type
-
options
extractSingle
or extractArray
(depending on whether the original query was for one record or
many records).
By default, ajax
method has the following behavior:
* It sets the response dataType
to "json"
* If the HTTP method is not "GET"
, it sets the Content-Type
to be
application/json; charset=utf-8
* If the HTTP method is not "GET"
, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
Returns:
beginPropertyChanges
()
Ember.Observable
private
endPropertyChanges()
to deliver the deferred change notifications and end
deferring.
Returns:
buildQuery
()
Overrides buildQuery method - Allows users to embed resources with findRecord OSF APIv2 does not have "include" functionality, instead we use 'embed'. Usage: findRecord(type, id, {include: 'resource'}) or findRecord(type, id, {include: ['resource1', resource2]}) Swaps included resources with embedded resources
buildURL
-
modelName
-
id
-
snapshot
-
requestType
-
query
/
.
When called by RESTAdapter.findMany() the id
and snapshot
parameters
will be arrays of ids and snapshots.
Parameters:
Returns:
cacheFor
-
keyName
Parameters:
-
keyName
String
Returns:
createRecord
-
store
-
type
-
snapshot
save
method on a model record instance.
The createRecord
method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by buildURL
.
See serialize
for information on how to customize the serialized form
of a record.
Parameters:
-
store
DS.Store -
type
DS.Model -
snapshot
DS.Snapshot
Returns:
dataForRequest
-
params
Parameters:
-
params
Object
Returns:
decrementProperty
-
keyName
-
decrement
`
javascript
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
`
Parameters:
Returns:
deleteRecord
-
store
-
type
-
snapshot
deleteRecord
method makes an Ajax (HTTP DELETE) request to a URL computed by buildURL
.
Parameters:
-
store
DS.Store -
type
DS.Model -
snapshot
DS.Snapshot
Returns:
destroy
()
Ember.Object
public
isDestroyed
flag and removing its
metadata, which effectively destroys observers and bindings.
If you try to set a property on a destroyed object, an exception will be
raised.
Note that destruction is scheduled for the end of the run loop and does not
happen immediately. It will set an isDestroying flag immediately.
Returns:
endPropertyChanges
()
Ember.Observable
private
beginPropertyChanges()
at the beginning of the changes to defer change
notifications. When you are done making changes, call this method to
deliver the deferred change notifications and end deferring.
Returns:
findAll
-
store
-
type
-
sinceToken
-
snapshotRecordArray
findAll
method makes an Ajax (HTTP GET) request to a URL computed by buildURL
, and returns a
promise for the resulting payload.
Parameters:
-
store
DS.Store -
type
DS.Model -
sinceToken
String -
snapshotRecordArray
DS.SnapshotRecordArray
Returns:
findBelongsTo
-
store
-
snapshot
-
url
links
).
For example, if your original payload looks like this:
`
js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
`
This method will be called with the parent record and /people/1/group
.
The findBelongsTo
method will make an Ajax (HTTP GET) request to the originally specified URL.
The format of your links
value will influence the final request URL via the urlPrefix
method:
* Links beginning with //
, http://
, https://
, will be used as is, with no further manipulation.
* Links beginning with a single /
will have the current adapter's host
value prepended to it.
* Links with no beginning /
will have a parentURL prepended to it, via the current adapter's buildURL
.
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshot -
url
String
Returns:
findHasMany
-
store
-
snapshot
-
url
links
).
For example, if your original payload looks like this:
`
js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
`
This method will be called with the parent record and /posts/1/comments
.
The findHasMany
method will make an Ajax (HTTP GET) request to the originally specified URL.
The format of your links
value will influence the final request URL via the urlPrefix
method:
* Links beginning with //
, http://
, https://
, will be used as is, with no further manipulation.
* Links beginning with a single /
will have the current adapter's host
value prepended to it.
* Links with no beginning /
will have a parentURL prepended to it, via the current adapter's buildURL
.
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshot -
url
String
Returns:
findRecord
-
store
-
type
-
id
-
snapshot
findRecord
method makes an Ajax request to a URL computed by
buildURL
, and returns a promise for the resulting payload.
This method performs an HTTP GET
request with the id provided as part of the query string.
Parameters:
-
store
DS.Store -
type
DS.Model -
id
String -
snapshot
DS.Snapshot
Returns:
generatedDetailedMessage
-
status
-
headers
-
payload
-
requestData
Returns:
generateIdForRecord
-
store
-
type
-
inputProperties
generateIdForRecord()
method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's primaryKey
.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls didCreateRecord()
. Only implement this method if
you intend to generate record IDs on the client-side.
The generateIdForRecord()
method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
`
javascript
import DS from 'ember-data';
import { v4 } from 'uuid';
export default DS.Adapter.extend({
generateIdForRecord: function(store, inputProperties) {
return v4();
}
});
`
Parameters:
Returns:
get
-
keyName
object[keyName]
or object.keyName
,
however it supports both computed properties and the unknownProperty
handler.
Because get
unifies the syntax for accessing all these kinds
of properties, it can make many refactorings easier, such as replacing a
simple property with a computed property, or vice versa.
### Computed Properties
Computed properties are methods defined with the property
modifier
declared at the end, such as:
`
javascript
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName')
`
When you call get
on a computed property, the function will be
called and the return value will be returned instead of the function
itself.
### Unknown Properties
Likewise, if you try to call get
on a property whose value is
undefined
, the unknownProperty()
method will be called on the object.
If this method returns any value other than undefined
, it will be returned
instead. This allows you to implement "virtual" properties that are
not defined upfront.
Parameters:
-
keyName
StringThe property to retrieve
Returns:
getProperties
-
list
getProperties
with a list of strings or an array:
`
javascript
record.getProperties('firstName', 'lastName', 'zipCode');
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
`
is equivalent to:
`
javascript
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
`
Parameters:
-
list
String... | Arrayof keys to get
Returns:
getWithDefault
-
keyName
-
defaultValue
undefined
.
`
javascript
person.getWithDefault('lastName', 'Doe');
`
Parameters:
Returns:
groupRecordsForFindMany
-
store
-
snapshots
findMany
.
This implementation groups together records that have the same base URL but
differing ids. For example /comments/1
and /comments/2
will be grouped together
because we know findMany can coalesce them together as /comments?ids[]=1&ids[]=2
It also supports urls where ids are passed as a query param, such as /comments?id=1
but not those where there is more than 1 query param such as /comments?id=2&name=David
Currently only the query param of id
is supported. If you need to support others, please
override this or the _stripIDFromURL
method.
It does not group records that have differing base urls, such as for example: /posts/1/comments/2
and /posts/2/comments/3
Returns:
findMany
.
handleResponse
-
status
-
headers
-
payload
-
requestData
DS.InvalidError
or a
DS.AdapterError
(or a sub class) from this hook and it will automatically
reject the promise and put your record into the invalid or error state.
Returning a DS.InvalidError
from this method will cause the
record to transition into the invalid
state and make the
errors
object available on the record. When returning an
DS.InvalidError
the store will attempt to normalize the error data
returned from the server using the serializer's extractErrors
method.
Parameters:
Returns:
hasObserverFor
-
key
true
if the object currently has observers registered for a
particular key. You can use this method to potentially defer performing
an expensive action until someone begins observing a particular property
on the object.
Parameters:
-
key
StringKey to check
Returns:
headersForRequest
-
params
headers
property of the adapter is
returned.
Parameters:
-
params
Object
Returns:
incrementProperty
-
keyName
-
increment
`
javascript
person.incrementProperty('age');
team.incrementProperty('score', 2);
`
Parameters:
Returns:
init
()
public
`
javascript
App.Person = Ember.Object.extend({
init: function() {
alert('Name is ' + this.get('name'));
}
});
var steve = App.Person.create({
name: "Steve"
});
// alerts 'Name is Steve'.
`
NOTE: If you do override init
for a framework class like Ember.View
,
be sure to call this._super(...arguments)
in your
init
declaration! If you don't, Ember may not have an opportunity to
do important setup work, and you'll see strange behavior in your
application.
isInvalid
-
status
-
headers
-
payload
handleResponse
implementation uses this hook to decide if the
response is a an invalid error.
Returns:
isSuccess
-
status
-
headers
-
payload
handleResponse
implementation uses this hook to decide if the
response is a success.
Returns:
methodForRequest
-
params
Parameters:
-
params
Object
Returns:
notifyPropertyChange
-
keyName
propertyWillChange
and propertyDidChange
in
succession.
Parameters:
-
keyName
StringThe property key to be notified about.
Returns:
propertyDidChange
-
keyName
get()
or set()
on it. In this case, you can use this
method and propertyWillChange()
instead. Calling these two methods
together will notify all observers that the property has potentially
changed value.
Note that you must always call propertyWillChange
and propertyDidChange
as a pair. If you do not, it may get the property change groups out of
order and cause notifications to be delivered more often than you would
like.
Parameters:
-
keyName
StringThe property key that has just changed.
Returns:
propertyWillChange
-
keyName
get()
or set()
on it. In this case, you can use this
method and propertyDidChange()
instead. Calling these two methods
together will notify all observers that the property has potentially
changed value.
Note that you must always call propertyWillChange
and propertyDidChange
as a pair. If you do not, it may get the property change groups out of
order and cause notifications to be delivered more often than you would
like.
Parameters:
-
keyName
StringThe property key that is about to change.
Returns:
query
-
store
-
type
-
query
query
method makes an Ajax (HTTP GET) request to a URL
computed by buildURL
, and returns a promise for the resulting
payload.
The query
argument is a simple JavaScript object that will be passed directly
to the server as parameters.
Returns:
queryRecord
-
store
-
type
-
query
queryRecord
method makes an Ajax (HTTP GET) request to a URL
computed by buildURL
, and returns a promise for the resulting
payload.
The query
argument is a simple JavaScript object that will be passed directly
to the server as parameters.
Returns:
removeObserver
-
key
-
target
-
method
addObserver()
and your
target will no longer receive notifications.
reopen
()
public
`
javascript
MyObject = Ember.Object.extend({
name: 'an object'
});
o = MyObject.create();
o.get('name'); // 'an object'
MyObject.reopen({
say: function(msg){
console.log(msg);
}
})
o2 = MyObject.create();
o2.say("hello"); // logs "hello"
o.say("goodbye"); // logs "goodbye"
`
To add functions and properties to the constructor itself,
see reopenClass
reopenClass
()
public
`
javascript
MyObject = Ember.Object.extend({
name: 'an object'
});
MyObject.reopenClass({
canBuild: false
});
MyObject.canBuild; // false
o = MyObject.create();
`
In other words, this creates static properties and functions for the class.
These are only available on the class and not on any instance of that class.
`
javascript
App.Person = Ember.Object.extend({
name : "",
sayHello : function() {
alert("Hello. My name is " + this.get('name'));
}
});
App.Person.reopenClass({
species : "Homo sapiens",
createPerson: function(newPersonsName){
return App.Person.create({
name:newPersonsName
});
}
});
var tom = App.Person.create({
name : "Tom Dale"
});
var yehuda = App.Person.createPerson("Yehuda Katz");
tom.sayHello(); // "Hello. My name is Tom Dale"
yehuda.sayHello(); // "Hello. My name is Yehuda Katz"
alert(App.Person.species); // "Homo sapiens"
`
Note that species
and createPerson
are *not* valid on the tom
and yehuda
variables. They are only valid on App.Person
.
To add functions and properties to instances of
a constructor by extending the constructor's prototype
see reopen
serialize
-
snapshot
-
options
serialize
method.
Example
`
app/adapters/application.js
import DS from 'ember-data';
export default DS.Adapter.extend({
createRecord: function(store, type, snapshot) {
var data = this.serialize(snapshot, { includeId: true });
var url = /${type.modelName}
;
// ...
}
});
`
Parameters:
-
snapshot
DS.Snapshot -
options
Object
Returns:
set
-
keyName
-
value
object[key] = value
or
object.key = value
, except that it provides support for computed
properties, the setUnknownProperty()
method and property observers.
### Computed Properties
If you try to set a value on a key that has a computed property handler
defined (see the get()
method for an example), then set()
will call
that method, passing both the value and key instead of simply changing
the value itself. This is useful for those times when you need to
implement a property that is composed of one or more member
properties.
### Unknown Properties
If you try to set a value on a key that is undefined in the target
object, then the setUnknownProperty()
handler will be called instead. This
gives you an opportunity to implement complex "virtual" properties that
are not predefined on the object. If setUnknownProperty()
returns
undefined, then set()
will simply set the value on the object.
### Property Observers
In addition to changing the property, set()
will also register a property
change with the object. Unless you have placed this call inside of a
beginPropertyChanges()
and endPropertyChanges(),
any "local" observers
(i.e. observer methods declared on the same object), will be called
immediately. Any "remote" observers (i.e. observer methods declared on
another object) will be placed in a queue and called at a later time in a
coalesced manner.
Returns:
setProperties
-
hash
beginPropertyChanges
and endPropertyChanges
batch, so
observers will be buffered.
`
javascript
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
`
Parameters:
-
hash
Objectthe hash of keys and values to set
Returns:
shouldBackgroundReloadAll
-
store
-
snapshotRecordArray
store.findAll
method resolves
with a cached record array.
This method is *only* checked by the store when the store is
returning a cached record array.
If this method returns true
the store will re-fetch all records
from the adapter.
For example, if you do not want to fetch complex data over a mobile
connection, or if the network is down, you can implement
shouldBackgroundReloadAll
as follows:
`
javascript
shouldBackgroundReloadAll: function(store, snapshotArray) {
var connection = window.navigator.connection;
if (connection === 'cellular' || connection === 'none') {
return false;
} else {
return true;
}
}
`
By default this method returns true
, indicating that a background reload
should always be triggered.
Parameters:
-
store
DS.Store -
snapshotRecordArray
DS.SnapshotRecordArray
Returns:
shouldBackgroundReloadRecord
-
store
-
snapshot
store.findRecord
method resolves a
cached record.
This method is *only* checked by the store when the store is
returning a cached record.
If this method returns true
the store will re-fetch a record from
the adapter.
For example, if you do not want to fetch complex data over a mobile
connection, or if the network is down, you can implement
shouldBackgroundReloadRecord
as follows:
`
javascript
shouldBackgroundReloadRecord: function(store, snapshot) {
var connection = window.navigator.connection;
if (connection === 'cellular' || connection === 'none') {
return false;
} else {
return true;
}
}
`
By default this hook returns true
so the data for the record is updated
in the background.
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshot
Returns:
shouldReloadAll
-
store
-
snapshotRecordArray
store.findAll
.
If this method returns true
, the store will re-fetch all records from
the adapter. If this method returns false
, the store will resolve
immediately using the cached records.
For example, if you are building an events ticketing system, in which users
can only reserve tickets for 20 minutes at a time, and want to ensure that
in each route you have data that is no more than 20 minutes old you could
write:
`
javascript
shouldReloadAll: function(store, snapshotArray) {
var snapshots = snapshotArray.snapshots();
return snapshots.any(function(ticketSnapshot) {
var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt')).minutes();
if (timeDiff > 20) {
return true;
} else {
return false;
}
});
}
`
This method would ensure that whenever you do store.findAll('ticket')
you
will always get a list of tickets that are no more than 20 minutes old. In
case a cached version is more than 20 minutes old, findAll
will not
resolve until you fetched the latest versions.
By default this methods returns true
if the passed snapshotRecordArray
is empty (meaning that there are no records locally available yet),
otherwise it returns false
.
Parameters:
-
store
DS.Store -
snapshotRecordArray
DS.SnapshotRecordArray
Returns:
shouldReloadRecord
-
store
-
snapshot
store.findRecord
.
If this method returns true
, the store will re-fetch a record from
the adapter. If this method returns false
, the store will resolve
immediately using the cached record.
For example, if you are building an events ticketing system, in which users
can only reserve tickets for 20 minutes at a time, and want to ensure that
in each route you have data that is no more than 20 minutes old you could
write:
`
javascript
shouldReloadRecord: function(store, ticketSnapshot) {
var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt')).minutes();
if (timeDiff > 20) {
return true;
} else {
return false;
}
}
`
This method would ensure that whenever you do `store.findRecord('ticket',
id)` you will always get a ticket that is no more than 20 minutes old. In
case the cached version is more than 20 minutes old, findRecord
will not
resolve until you fetched the latest version.
By default this hook returns false
, as most UIs should not block user
interactions while waiting on data update.
Parameters:
-
store
DS.Store -
snapshot
DS.Snapshot
Returns:
sortQueryParams
-
obj
`
js
store.query('posts', { sort: 'price', category: 'pets' });
`
will generate a requests like this /posts?category=pets&sort=price
, even if the
parameters were specified in a different order.
That way the generated URL will be deterministic and that simplifies caching mechanisms
in the backend.
Setting sortQueryParams
to a falsey value will respect the original order.
In case you want to sort the query parameters with a different criteria, set
sortQueryParams
to your custom sort function.
`
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
sortQueryParams: function(params) {
var sortedKeys = Object.keys(params).sort().reverse();
var len = sortedKeys.length, newParams = {};
for (var i = 0; i < len; i++) {
newParams[sortedKeys[i]] = params[sortedKeys[i]];
}
return newParams;
}
});
`
Parameters:
-
obj
Object
Returns:
toggleProperty
-
keyName
`
javascript
starship.toggleProperty('warpDriveEngaged');
`
Parameters:
-
keyName
StringThe name of the property to toggle
Returns:
toString
()
String
public
toString
typically does, in a generic way for all Ember
objects.
`
javascript
App.Person = Em.Object.extend()
person = App.Person.create()
person.toString() //=> "`
If the object's class is not defined on an Ember namespace, it will
indicate it is a subclass of the registered superclass:
`
javascript
Student = App.Person.extend()
student = Student.create()
student.toString() //=> "<(subclass of App.Person):ember1025>"
`
If the method toStringExtension
is defined, its return value will be
included in the output.
`
javascript
App.Teacher = App.Person.extend({
toStringExtension: function() {
return this.get('fullName');
}
});
teacher = App.Teacher.create()
teacher.toString(); //=> "`
Returns:
updateRecord
-
store
-
type
-
snapshot
Parameters:
-
store
DS.Store -
type
DS.Model -
snapshot
DS.Snapshot
Returns:
urlForCreateRecord
-
modelName
-
snapshot
Parameters:
-
modelName
String -
snapshot
DS.Snapshot
Returns:
urlForDeleteRecord
-
id
-
modelName
-
snapshot
Parameters:
-
id
String -
modelName
String -
snapshot
DS.Snapshot
Returns:
urlForFindAll
-
modelName
-
snapshot
Parameters:
-
modelName
String -
snapshot
DS.SnapshotRecordArray
Returns:
urlForFindBelongsTo
-
id
-
modelName
-
snapshot
Parameters:
-
id
String -
modelName
String -
snapshot
DS.Snapshot
Returns:
urlForFindHasMany
-
id
-
modelName
-
snapshot
Parameters:
-
id
String -
modelName
String -
snapshot
DS.Snapshot
Returns:
urlForFindRecord
-
id
-
modelName
-
snapshot
Parameters:
-
id
String -
modelName
String -
snapshot
DS.Snapshot
Returns:
urlForRequest
-
params
Parameters:
-
params
Object
Returns:
urlForUpdateRecord
-
id
-
modelName
-
snapshot
Parameters:
-
id
String -
modelName
String -
snapshot
DS.Snapshot
Returns:
willDestroy
()
public
Properties
coalesceFindRequests
Boolean
store.find
or from accessing a relationship separately to the server. If your server supports passing
ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests
within a single runloop.
For example, if you have an initial payload of:
`
javascript
{
post: {
id: 1,
comments: [1, 2]
}
}
`
By default calling post.get('comments')
will trigger the following requests(assuming the
comments haven't been loaded before):
`
GET /comments/1
GET /comments/2
`
If you set coalesceFindRequests to true
it will instead trigger the following request:
`
GET /comments?filter[id]=1,2
`
Setting coalesceFindRequests to true
also works for store.find
requests and belongsTo
relationships accessed within the same runloop. If you set coalesceFindRequests: true
`
javascript
store.findRecord('comment', 1);
store.findRecord('comment', 2);
`
will also send a request to: GET /comments?filter[id]=1,2
Note: Requests coalescing rely on URL building strategy. So if you override buildURL
in your app
groupRecordsForFindMany
more likely should be overridden as well in order for coalescing to work.
concatenatedProperties
Array
public
classNames
property of Ember.View
.
Here is some sample code showing the difference between a concatenated
property and a normal one:
`
javascript
App.BarView = Ember.View.extend({
someNonConcatenatedProperty: ['bar'],
classNames: ['bar']
});
App.FooBarView = App.BarView.extend({
someNonConcatenatedProperty: ['foo'],
classNames: ['foo']
});
var fooBarView = App.FooBarView.create();
fooBarView.get('someNonConcatenatedProperty'); // ['foo']
fooBarView.get('classNames'); // ['ember-view', 'bar', 'foo']
`
This behavior extends to object creation as well. Continuing the
above example:
`
javascript
var view = App.FooBarView.create({
someNonConcatenatedProperty: ['baz'],
classNames: ['baz']
})
view.get('someNonConcatenatedProperty'); // ['baz']
view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz']
`
Adding a single property that is not an array will just add it in the array:
`
javascript
var view = App.FooBarView.create({
classNames: 'baz'
})
view.get('classNames'); // ['ember-view', 'bar', 'foo', 'baz']
`
Using the concatenatedProperties
property, we can tell Ember to mix the
content of the properties.
In Ember.View
the classNameBindings
and attributeBindings
properties
are also concatenated, in addition to classNames
.
This feature is available for you to use throughout the Ember object model,
although typical app developers are likely to use it infrequently. Since
it changes expectations about behavior of properties, you should properly
document its usage in each individual concatenated property (to not
mislead your users to think they can override the property in a subclass).
Default: null
defaultSerializer
String
defaultSerializer
property to be the name of the custom
serializer.
Note the defaultSerializer
serializer has a lower priority than
a model specific serializer (i.e. PostSerializer
) or the
application
serializer.
`
app/adapters/django.js
import DS from 'ember-data';
export default DS.Adapter.extend({
defaultSerializer: 'django'
});
`
headers
Object
RESTAdapter
's headers
object and Ember Data will send them
along with each ajax request. For dynamic headers see [headers
customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization).
`
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
`
host
String
host
property.
`
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
host: 'https://api.example.com'
});
`
Requests for the Post
model would now target https://api.example.com/post/
.
isDestroyed
Unknown
public
true
the observers and bindings were already
removed by the effect of calling the destroy()
method.
Default: false
isDestroying
Unknown
public
destroy()
method has been called.
The object stays intact until the end of the run loop at which point
the isDestroyed
flag is set.
Default: false
mergedProperties
Array
public
queryParams
property of routes.
Here is some sample code showing the difference between a merged
property and a normal one:
`
javascript
App.BarRoute = Ember.Route.extend({
someNonMergedProperty: {
nonMerged: 'superclass value of nonMerged'
},
queryParams: {
page: {replace: false},
limit: {replace: true}
}
});
App.FooBarRoute = App.BarRoute.extend({
someNonMergedProperty: {
completelyNonMerged: 'subclass value of nonMerged'
},
queryParams: {
limit: {replace: false}
}
});
var fooBarRoute = App.FooBarRoute.create();
fooBarRoute.get('someNonMergedProperty');
// => { completelyNonMerged: 'subclass value of nonMerged' }
//
// Note the entire object, including the nonMerged property of
// the superclass object, has been replaced
fooBarRoute.get('queryParams');
// => {
// page: {replace: false},
// limit: {replace: false}
// }
//
// Note the page remains from the superclass, and the
// limit
property's value of false
has been merged from
// the subclass.
`
This behavior is not available during object create
calls. It is only
available at extend
time.
This feature is available for you to use throughout the Ember object model,
although typical app developers are likely to use it infrequently. Since
it changes expectations about behavior of properties, you should properly
document its usage in each individual merged property (to not
mislead your users to think they can override the property in a subclass).
Default: null
namespace
String
namespace
by setting the namespace
property on the adapter:
`
app/adapters/application.js
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'api/1'
});
`
Requests for the Post
model would now target /api/1/post/
.