OsfSerializer Class
Base serializer class for all OSF APIv2 endpoints. Provides custom behaviors for embeds, relationships, and pagination.
Item Index
Methods
- _canSerialize
- _extractEmbeds
- _extractType
- _getMappedKey
- _lazyInjections
- _mustSerialize
- _normalizeDocumentHelper
- _normalizeRelationshipDataHelper
- _normalizeResourceHelper
- _normalizeResponse
- _onLookup
- _scheduledDestroy
- _shouldSerializeHasMany
- addObserver
- applyTransforms
- beginPropertyChanges
- cacheFor
- decrementProperty
- destroy
- endPropertyChanges
- extractAttributes
- extractErrors
- extractId
- extractMeta
- extractPolymorphicRelationship
- extractRelationship
- extractRelationships
- get
- getProperties
- getWithDefault
- hasObserverFor
- incrementProperty
- init
- keyForAttribute
- keyForLink
- keyForRelationship
- modelNameFromPayloadKey
- modelNameFromPayloadType
- normalize
- normalizeArrayResponse
- normalizeAttributes
- normalizeCreateRecordResponse
- normalizeDeleteRecordResponse
- normalizeFindAllResponse
- normalizeFindBelongsToResponse
- normalizeFindHasManyResponse
- normalizeFindManyResponse
- normalizeFindRecordResponse
- normalizeQueryRecordResponse
- normalizeQueryResponse
- normalizeRelationships
- normalizeResponse
- normalizeSaveResponse
- normalizeSingleResponse
- normalizeUpdateRecordResponse
- normalizeUsingDeclaredMapping
- notifyPropertyChange
- payloadKeyFromModelName
- payloadTypeFromModelName
- propertyDidChange
- propertyWillChange
- pushPayload
- removeObserver
- reopen
- reopenClass
- serialize
- serializeAttribute
- serializeBelongsTo
- serializeHasMany
- serializeIntoHash
- serializePolymorphicType
- set
- setProperties
- shouldSerializeHasMany
- toggleProperty
- toString
- transformFor
- willDestroy
Methods
_canSerialize
(
Boolean
private
-
key
Check attrs.key.serialize property to inform if the
key
can be serialized
Parameters:
-
key
String
Returns:
Boolean:
true if the key can be serialized
_extractEmbeds
(
Array
private
-
resourceHash
Extract information about records embedded inside this request
Parameters:
-
resourceHash
Object
Returns:
_getMappedKey
(
String
private
-
key
Looks up the property key that was set by the custom
attr
mapping
passed to the serializer.
Parameters:
-
key
String
Returns:
String:
key
_lazyInjections
()
Object
private
Returns a hash of property names and container names that injected
properties will lookup on the container lazily.
Returns:
Object:
Hash of all lazy injected property keys to container names
_mustSerialize
(
Boolean
private
-
key
When attrs.key.serialize is set to true then
it takes priority over the other checks and the related
attribute/relationship will be serialized
Parameters:
-
key
String
Returns:
Boolean:
true if the key must be serialized
_normalizeRelationshipDataHelper
(
Object
private
-
relationshipDataHash
Parameters:
-
relationshipDataHash
Object
Returns:
_normalizeResponse
(
Object
private
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
-
isSingle
Parameters:
Returns:
Object:
JSON-API Document
_onLookup
()
private
Provides lookup-time type validation for injected properties.
_scheduledDestroy
()
private
Invoked by the run loop to actually destroy the object. This is
scheduled for execution by the
destroy
method.
_shouldSerializeHasMany
(
Boolean
private
-
snapshot
-
key
-
relationshipType
Check if the given hasMany relationship should be serialized
Parameters:
-
snapshot
DS.Snapshot -
key
String -
relationshipType
String
Returns:
Boolean:
true if the hasMany relationship should be serialized
addObserver
(
public
-
key
-
target
-
method
Adds an observer on a property.
This is the core method used to register an observer for a property.
Once you call this method, any time the key's value is set, your observer
will be notified. Note that the observers are triggered any time the
value is set, regardless of whether it has actually changed. Your
observer should be prepared to handle that.
You can also pass an optional context parameter to this method. The
context will be passed to your observer method whenever it is triggered.
Note that if you add the same target/method pair on a key multiple times
with different context parameters, your observer will only be called once
with the last context you passed.
### Observer Methods
Observer methods you pass should generally have the following signature if
you do not pass a
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.
applyTransforms
(
Object
private
-
typeClass
-
data
Given a subclass of
DS.Model
and a JSON object this method will
iterate through each attribute of the DS.Model
and invoke the
DS.Transform#deserialize
method on the matching property of the
JSON object. This method is typically called after the
serializer's normalize
method.
Returns:
Object:
data The transformed data object
beginPropertyChanges
()
Ember.Observable
private
Begins a grouping of property changes.
You can use this method to group property changes so that notifications
will not be sent until the changes are finished. If you plan to make a
large number of changes to an object at one time, you should call this
method at the beginning of the changes to begin deferring change
notifications. When you are done making changes, call
endPropertyChanges()
to deliver the deferred change notifications and end
deferring.
Returns:
cacheFor
(
Object
public
-
keyName
Returns the cached value of a computed property, if it exists.
This allows you to inspect the value of a computed property
without accidentally invoking it if it is intended to be
generated lazily.
Parameters:
-
keyName
String
Returns:
Object:
The cached value of the computed property, if any
decrementProperty
(
Number
public
-
keyName
-
decrement
Set the value of a property to the current value minus some amount.
`
javascript
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
`
Parameters:
Returns:
Number:
The new property value
destroy
()
Ember.Object
public
Destroys an object by setting the
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:
Ember.Object:
receiver
endPropertyChanges
()
Ember.Observable
private
Ends a grouping of property changes.
You can use this method to group property changes so that notifications
will not be sent until the changes are finished. If you plan to make a
large number of changes to an object at one time, you should call
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:
extractErrors
(
Object
-
store
-
typeClass
-
payload
-
id
extractErrors
is used to extract model errors when a call
to DS.Model#save
fails with an InvalidError
. By default
Ember Data expects error information to be located on the errors
property of the payload object.
This serializer expects this errors
object to be an Array similar
to the following, compliant with the JSON-API specification:
`
js
{
"errors": [
{
"detail": "This username is already taken!",
"source": {
"pointer": "data/attributes/username"
}
}, {
"detail": "Doesn't look like a valid email.",
"source": {
"pointer": "data/attributes/email"
}
}
]
}
`
The key detail
provides a textual description of the problem.
Alternatively, the key title
can be used for the same purpose.
The nested keys source.pointer
detail which specific element
of the request data was invalid.
Note that JSON-API also allows for object-level errors to be placed
in an object with pointer data
, signifying that the problem
cannot be traced to a specific attribute:
`
javascript
{
"errors": [
{
"detail": "Some generic non property error message",
"source": {
"pointer": "data"
}
}
]
}
`
When turn into a DS.Errors
object, you can read these errors
through the property base
:
`
handlebars
{{#each model.errors.base as |error|}}
{{error.message}}
{{/each}}
`
Example of alternative implementation, overriding the default
behavior to deal with a different format of errors:
`
app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractErrors: function(store, typeClass, payload, id) {
if (payload && typeof payload === 'object' && payload._problems) {
payload = payload._problems;
this.normalizeErrors(typeClass, payload);
}
return payload;
}
});
`
Returns:
Object:
json The deserialized errors
extractMeta
(
-
store
-
modelClass
-
payload
extractMeta
is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the meta
property of the payload object.
Example
`
app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
extractMeta: function(store, typeClass, payload) {
if (payload && payload.hasOwnProperty('_pagination')) {
let meta = payload._pagination;
delete payload._pagination;
return meta;
}
}
});
`
extractPolymorphicRelationship
(
Object
-
relationshipModelName
-
relationshipHash
-
relationshipOptions
Returns a polymorphic relationship formatted as a JSON-API "relationship object".
http://jsonapi.org/format/#document-resource-object-relationships
relationshipOptions
is a hash which contains more information about the
polymorphic relationship which should be extracted:
- resourceHash
complete hash of the resource the relationship should be
extracted from
- relationshipKey
key under which the value for the relationship is
extracted from the resourceHash
- relationshipMeta
meta information about the relationship
Returns:
get
(
Object
public
-
keyName
Retrieves the value of a property from the object.
This method is usually similar to using
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:
Object:
The property value or undefined.
getProperties
(
Object
public
-
list
To get the values of multiple properties at once, call
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
(
Object
public
-
keyName
-
defaultValue
Retrieves the value of a property, or a default value in the case that the
property returns
undefined
.
`
javascript
person.getWithDefault('lastName', 'Doe');
`
Parameters:
Returns:
Object:
The property value or the defaultValue.
hasObserverFor
(
Boolean
private
-
key
Returns
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:
incrementProperty
(
Number
public
-
keyName
-
increment
Set the value of a property to the current value plus some amount.
`
javascript
person.incrementProperty('age');
team.incrementProperty('score', 2);
`
Parameters:
Returns:
Number:
The new property value
init
()
public
An overridable method called when objects are instantiated. By default,
does nothing unless it is overridden during class definition.
Example:
`
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.
keyForAttribute
(
String
-
key
-
method
keyForAttribute
can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
By default JSONAPISerializer
follows the format used on the examples of
http://jsonapi.org/format and uses dashes as the word separator in the JSON
attribute keys.
This behaviour can be easily customized by extending this method.
Example
`
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
keyForAttribute: function(attr, method) {
return Ember.String.dasherize(attr).toUpperCase();
}
});
`
Returns:
String:
normalized key
keyForLink
(
String
-
key
-
kind
keyForLink
can be used to define a custom key when deserializing link
properties.
Returns:
String:
normalized key
keyForRelationship
(
String
-
key
-
typeClass
-
method
keyForRelationship
can be used to define a custom key when
serializing and deserializing relationship properties.
By default JSONAPISerializer
follows the format used on the examples of
http://jsonapi.org/format and uses dashes as word separators in
relationship properties.
This behaviour can be easily customized by extending this method.
Example
`
app/serializers/post.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
keyForRelationship: function(key, relationship, method) {
return Ember.String.underscore(key);
}
});
`
Returns:
String:
normalized key
modelNameFromPayloadKey
(
String
-
key
Parameters:
-
key
String
Returns:
String:
the model's modelName
modelNameFromPayloadType
(
String
public
-
payloadType
modelNameFromPayloadType
can be used to change the mapping for a DS model
name, taken from the value in the payload.
Say your API namespaces the type of a model and returns the following
payload for the post
model:
`
javascript
// GET /api/posts/1
{
"data": {
"id": 1,
"type: "api::v1::post"
}
}
`
By overwriting modelNameFromPayloadType
you can specify that the
posr
model should be used:
`
app/serializers/application.js
import DS from "ember-data";
export default DS.JSONAPISerializer.extend({
modelNameFromPayloadType(payloadType) {
return payloadType.replace('api::v1::', '');
}
});
`
By default the modelName for a model is its singularized name in dasherized
form. Usually, Ember Data can use the correct inflection to do this for
you. Most of the time, you won't need to override
modelNameFromPayloadType
for this purpose.
Also take a look at
[payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize
how the type of a record should be serialized.
Parameters:
-
payloadType
Stringtype from payload
Returns:
String:
modelName
normalizeArrayResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeAttributes
()
private
normalizeCreateRecordResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeDeleteRecordResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeFindAllResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeFindBelongsToResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeFindHasManyResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeFindManyResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeFindRecordResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeQueryRecordResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeQueryResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeRelationships
()
private
normalizeResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
The
normalizeResponse
method is used to normalize a payload from the
server to a JSON-API Document.
http://jsonapi.org/format/#document-structure
This method delegates to a more specific normalize method based on
the requestType
.
To override this method with a custom one, make sure to call
return this._super(store, primaryModelClass, payload, id, requestType)
with your
pre-processed data.
Here's an example of using normalizeResponse
manually:
`
javascript
socket.on('message', function(message) {
var data = message.data;
var modelClass = store.modelFor(data.modelName);
var serializer = store.serializerFor(data.modelName);
var normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id);
store.push(normalized);
});
`
Parameters:
Returns:
Object:
JSON-API Document
normalizeSaveResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeSingleResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeUpdateRecordResponse
(
Object
-
store
-
primaryModelClass
-
payload
-
id
-
requestType
Parameters:
Returns:
Object:
JSON-API Document
normalizeUsingDeclaredMapping
()
private
notifyPropertyChange
(
Ember.Observable
public
-
keyName
Convenience method to call
propertyWillChange
and propertyDidChange
in
succession.
Parameters:
-
keyName
StringThe property key to be notified about.
Returns:
payloadTypeFromModelName
(
String
public
-
modelname
payloadTypeFromModelName
can be used to change the mapping for the type in
the payload, taken from the model name.
Say your API namespaces the type of a model and expects the following
payload when you update the post
model:
`
javascript
// POST /api/posts/1
{
"data": {
"id": 1,
"type": "api::v1::post"
}
}
`
By overwriting payloadTypeFromModelName
you can specify that the
namespaces model name for the post
should be used:
`
app/serializers/application.js
import DS from "ember-data";
export default JSONAPISerializer.extend({
payloadTypeFromModelName(modelName) {
return "api::v1::" + modelName;
}
});
`
By default the payload type is the pluralized model name. Usually, Ember
Data can use the correct inflection to do this for you. Most of the time,
you won't need to override payloadTypeFromModelName
for this purpose.
Also take a look at
[modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize
how the model name from should be mapped from the payload.
Parameters:
-
modelname
StringmodelName from the record
Returns:
String:
payloadType
propertyDidChange
(
Ember.Observable
private
-
keyName
Notify the observer system that a property has just changed.
Sometimes you need to change a value directly or indirectly without
actually calling
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
(
Ember.Observable
private
-
keyName
Notify the observer system that a property is about to change.
Sometimes you need to change a value directly or indirectly without
actually calling
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:
removeObserver
(
public
-
key
-
target
-
method
Remove an observer you have previously registered on this object. Pass
the same key, target, and method you passed to
addObserver()
and your
target will no longer receive notifications.
reopen
()
public
Augments a constructor's prototype with additional
properties and functions:
`
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
Augments a constructor's own properties and functions:
`
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
(
Object
-
snapshot
-
options
Parameters:
-
snapshot
DS.Snapshot -
options
Object
Returns:
Object:
json
serializeAttribute
(
-
snapshot
-
json
-
key
-
attribute
Parameters:
-
snapshot
DS.Snapshot -
json
Object -
key
String -
attribute
Object
serializeBelongsTo
(
-
snapshot
-
json
-
relationship
Parameters:
-
snapshot
DS.Snapshot -
json
Object -
relationship
Object
serializeHasMany
(
-
snapshot
-
json
-
relationship
Parameters:
-
snapshot
DS.Snapshot -
json
Object -
relationship
Object
serializeIntoHash
(
-
hash
-
typeClass
-
snapshot
-
options
You can use this method to customize how a serialized record is added to the complete
JSON hash to be sent to the server. By default the JSON Serializer does not namespace
the payload and just sends the raw serialized JSON object.
If your server expects namespaced keys, you should consider using the RESTSerializer.
Otherwise you can override this method to customize how the record is added to the hash.
The hash property should be modified by reference.
For example, your server may expect underscored root objects.
`
app/serializers/application.js
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, snapshot, options) {
var root = Ember.String.decamelize(type.modelName);
data[root] = this.serialize(snapshot, options);
}
});
`
Parameters:
-
hash
Object -
typeClass
DS.Model -
snapshot
DS.Snapshot -
options
Object
serializePolymorphicType
(
-
snapshot
-
json
-
relationship
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
{ polymorphic: true }
is pass as the second argument to the
DS.belongsTo
function.
Example
`
app/serializers/comment.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
serializePolymorphicType: function(snapshot, json, relationship) {
var key = relationship.key,
belongsTo = snapshot.belongsTo(key);
key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key;
if (Ember.isNone(belongsTo)) {
json[key + "_type"] = null;
} else {
json[key + "_type"] = belongsTo.modelName;
}
}
});
`
Parameters:
-
snapshot
DS.Snapshot -
json
Object -
relationship
Object
set
(
Object
public
-
keyName
-
value
Sets the provided key or path to the value.
This method is generally very similar to calling
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:
Object:
The passed value
setProperties
(
Object
public
-
hash
Sets a list of properties at once. These properties are set inside
a single
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:
Object:
The passed in hash
shouldSerializeHasMany
(
Boolean
-
snapshot
-
key
-
relationshipType
Check if the given hasMany relationship should be serialized
Parameters:
-
snapshot
DS.Snapshot -
key
String -
relationshipType
String
Returns:
Boolean:
true if the hasMany relationship should be serialized
toggleProperty
(
Boolean
public
-
keyName
Set the value of a boolean property to the opposite of its
current value.
`
javascript
starship.toggleProperty('warpDriveEngaged');
`
Parameters:
-
keyName
StringThe name of the property to toggle
Returns:
Boolean:
The new property value
toString
()
String
public
Returns a string representation which attempts to provide more information
than Javascript's "
"
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:
String:
string representation
willDestroy
()
public
Override to implement teardown.
Properties
attrs
Object
The
attrs
object can be used to declare a simple mapping between
property names on DS.Model
records and payload keys in the
serialized JSON object representing the record. An object with the
property key
can also be used to designate the attribute's key on
the response payload.
Example
`
app/models/person.js
import DS from 'ember-data';
export default DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
`
`
app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: { key: 'career' }
}
});
`
You can also remove attributes by setting the serialize
key to
false
in your mapping object.
Example
`
app/serializers/person.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
attrs: {
admin: { serialize: false },
occupation: { key: 'career' }
}
});
`
When serialized:
`
javascript
{
"firstName": "Harry",
"lastName": "Houdini",
"career": "magician"
}
`
Note that the admin
is now not included in the payload.
concatenatedProperties
Array
public
Defines the properties that will be concatenated from the superclass
(instead of overridden).
By default, when you extend an Ember class a property defined in
the subclass overrides a property with the same name that is defined
in the superclass. However, there are some cases where it is preferable
to build up a property's value by combining the superclass' property
value with the subclass' value. An example of this in use within Ember
is the
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
isDestroyed
Unknown
public
Destroyed object property flag.
if this property is
true
the observers and bindings were already
removed by the effect of calling the destroy()
method.
Default: false
isDestroying
Unknown
public
Destruction scheduled flag. The
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
Defines the properties that will be merged from the superclass
(instead of overridden).
By default, when you extend an Ember class a property defined in
the subclass overrides a property with the same name that is defined
in the superclass. However, there are some cases where it is preferable
to build up a property's value by merging the superclass property value
with the subclass property's value. An example of this in use within Ember
is the
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
primaryKey
String
The
primaryKey
is used when serializing and deserializing
data. Ember Data always uses the id
property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey
property to match the primaryKey
of your external
store.
Example
`
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: '_id'
});
`
Default: 'id'
store
DS.Store
public
The
store
property is the application's store
that contains all records.
It's injected as a service.
It can be used to push records from a non flat data structure server
response.