Model Class
Attribute-based data model with APIs for getting, setting, validating, and syncing attribute values, as well as events for being notified of model changes.
In most cases, you'll want to create your own subclass of Y.Model
and
customize it to meet your needs. In particular, the sync()
and validate()
methods are meant to be overridden by custom implementations. You may also want
to override the parse()
method to parse non-generic server responses.
Constructor
Model
()
Item Index
Methods
- addAttrs
- addTarget
- after
- attrAdded
- before
- bubble
- destroy
- detach
- detachAll
- fire
- generateClientId
- get
- getAsHTML
- getAsURL
- getAttrs
- getEvent
- getTargets
- init
- isModified
- isNew
- load
- modifyAttr
- on
- once
- onceAfter
- parse
- parseType
- publish
- removeAttr
- removeTarget
- reset
- save
- set
- setAttrs
- subscribe deprecated
- sync
- toJSON
- toString
- undo
- unsubscribe deprecated
- unsubscribeAll deprecated
- validate
Properties
- changed
- idAttribute
- lastChange
- lists
- name deprecated
Attributes
Methods
addAttrs
-
cfgs
-
values
-
lazy
Configures a group of attributes, and sets initial values.
NOTE: This method does not isolate the configuration object by merging/cloning. The caller is responsible for merging/cloning the configuration object if required.
Parameters:
-
cfgs
ObjectAn object with attribute name/configuration pairs.
-
values
ObjectAn object with attribute name/value pairs, defining the initial values to apply. Values defined in the cfgs argument will be over-written by values in this argument unless defined as read only.
-
lazy
BooleanWhether or not to delay the intialization of these attributes until the first call to get/set. Individual attributes can over-ride this behavior by defining a lazyAdd configuration property in their configuration. See addAttr.
Returns:
A reference to the host object.
addTarget
-
o
Registers another EventTarget as a bubble target. Bubble order is determined by the order registered. Multiple targets can be specified.
Events can only bubble if emitFacade is true.
Included in the event-custom-complex submodule.
Parameters:
-
o
EventTargetthe target to add
after
-
type
-
fn
-
[context]
-
[arg*]
Subscribe to a custom event hosted by this object. The supplied callback will execute after any listeners add via the subscribe method, and after the default function, if configured for the event, has executed.
Parameters:
Returns:
A subscription handle capable of detaching the subscription
attrAdded
-
name
Checks if the given attribute has been added to the host
Parameters:
-
name
StringThe name of the attribute to check.
Returns:
true if an attribute with the given name has been added, false if it hasn't. This method will return true for lazily added attributes.
before
()
Executes the callback before a DOM event, custom event or method. If the first argument is a function, it is assumed the target is a method. For DOM and custom events, this is an alias for Y.on.
For DOM and custom events: type, callback, context, 0-n arguments
For methods: callback, object (method host), methodName, context, 0-n arguments
Returns:
detach handle
bubble
-
evt
Propagate an event. Requires the event-custom-complex module.
Parameters:
-
evt
CustomEventthe custom event to propagate
Returns:
the aggregated return value from Event.Custom.fire
destroy
-
[options]
-
[callback]
Destroys this model instance and removes it from its containing lists, if any.
The callback, if one is provided, will be called after the model is destroyed.
If options.remove
is true
, then this method delegates to the sync()
method to delete the model from the persistence layer, which is an
asynchronous action. In this case, the callback (if provided) will be
called after the sync layer indicates success or failure of the delete
operation.
Parameters:
-
[options]
Object optionalSync options. It's up to the custom sync implementation to determine what options it supports or requires, if any.
-
[remove=false]
Boolean optionalIf
true
, the model will be deleted via the sync layer in addition to the instance being destroyed.
-
-
[callback]
Function optionalCalled after the model has been destroyed (and deleted via the sync layer if
options.remove
istrue
).-
err
Error | NullIf an error occurred, this parameter will contain the error. Otherwise err will be
null
.
-
detach
-
type
-
fn
-
context
Detach one or more listeners the from the specified event
Parameters:
-
type
String | ObjectEither the handle to the subscriber or the type of event. If the type is not specified, it will attempt to remove the listener from all hosted events.
-
fn
FunctionThe subscribed function to unsubscribe, if not supplied, all subscribers will be removed.
-
context
ObjectThe custom object passed to subscribe. This is optional, but if supplied will be used to disambiguate multiple listeners that are the same (e.g., you subscribe many object using a function that lives on the prototype)
Returns:
the host
detachAll
-
type
Removes all listeners from the specified event. If the event type is not specified, all listeners from all hosted custom events will be removed.
Parameters:
-
type
StringThe type, or name of the event
fire
-
type
-
arguments
Fire a custom event by name. The callback functions will be executed from the context specified when the event was created, and with the following parameters.
The first argument is the event type, and any additional arguments are passed to the listeners as parameters. If the first of these is an object literal, and the event is configured to emit an event facade, that object is mixed into the event facade and the facade is provided in place of the original object.
If the custom event object hasn't been created, then the event hasn't been published and it has no subscribers. For performance sake, we immediate exit in this case. This means the event won't bubble, so if the intention is that a bubble target be notified, the event must be published on this object first.
Parameters:
-
type
String | ObjectThe type of the event, or an object that contains a 'type' property.
-
arguments
Object*an arbitrary set of parameters to pass to the handler. If the first of these is an object literal and the event is configured to emit an event facade, the event facade will replace that parameter after the properties the object literal contains are copied to the event facade.
Returns:
True if the whole lifecycle of the event went through, false if at any point the event propagation was halted.
generateClientId
()
String
Returns a clientId string that's unique among all models on the current page (even models in other YUI instances). Uniqueness across pageviews is unlikely.
Returns:
Unique clientId.
get
-
name
Returns the value of the specified attribute.
If the attribute's value is an object, name may use dot notation to specify the path to a specific property within the object, and the value of that property will be returned.
Parameters:
-
name
StringAttribute name or object property path.
Returns:
Attribute value, or undefined
if the attribute doesn't
exist.
Example:
// Set the 'foo' attribute to an object.
myModel.set('foo', {
bar: {
baz: 'quux'
}
});
// Get the value of 'foo'.
myModel.get('foo');
// => {bar: {baz: 'quux'}}
// Get the value of 'foo.bar.baz'.
myModel.get('foo.bar.baz');
// => 'quux'
getAsHTML
-
name
Returns an HTML-escaped version of the value of the specified string
attribute. The value is escaped using Y.Escape.html()
.
Parameters:
-
name
StringAttribute name or object property path.
Returns:
HTML-escaped attribute value.
getAsURL
-
name
Returns a URL-encoded version of the value of the specified string
attribute. The value is encoded using the native encodeURIComponent()
function.
Parameters:
-
name
StringAttribute name or object property path.
Returns:
URL-encoded attribute value.
getAttrs
-
attrs
Gets multiple attribute values.
Parameters:
Returns:
An object with attribute name/value pairs.
getEvent
-
type
-
prefixed
Returns the custom event of the provided type has been created, a falsy value otherwise
Parameters:
Returns:
the custom event or null
getTargets
()
Returns an array of bubble targets for this object.
Returns:
EventTarget[]
init
-
cfg
Init lifecycle method, invoked during construction. Sets up attributes and invokes initializers for the class hierarchy.
Parameters:
-
cfg
ObjectObject with configuration property name/value pairs
Returns:
A reference to this object
isModified
()
Boolean
Returns true
if any attribute of this model has been changed since the
model was last saved.
New models (models for which isNew()
returns true
) are implicitly
considered to be "modified" until the first time they're saved.
Returns:
true
if this model has changed since it was last saved,
false
otherwise.
isNew
()
Boolean
Returns true
if this model is "new", meaning it hasn't been saved since it
was created.
Newness is determined by checking whether the model's id
attribute has
been set. An empty id is assumed to indicate a new model, whereas a
non-empty id indicates a model that was either loaded or has been saved
since it was created.
Returns:
true
if this model is new, false
otherwise.
load
-
[options]
-
[callback]
Loads this model from the server.
This method delegates to the sync()
method to perform the actual load
operation, which is an asynchronous action. Specify a callback function to
be notified of success or failure.
A successful load operation will fire a load
event, while an unsuccessful
load operation will fire an error
event with the src
value "load".
If the load operation succeeds and one or more of the loaded attributes
differ from this model's current attributes, a change
event will be fired.
Parameters:
-
[options]
Object optionalOptions to be passed to
sync()
and toset()
when setting the loaded attributes. It's up to the custom sync implementation to determine what options it supports or requires, if any. -
[callback]
Function optionalCalled when the sync operation finishes.
-
err
Error | NullIf an error occurred, this parameter will contain the error. If the sync operation succeeded, err will be
null
. -
response
AnyThe server's response. This value will be passed to the
parse()
method, which is expected to parse it and return an attribute hash.
-
modifyAttr
-
name
-
config
Updates the configuration of an attribute which has already been added.
The properties which can be modified through this interface are limited to the following subset of attributes, which can be safely modified after a value has already been set on the attribute:
- readOnly;
- writeOnce;
- broadcast; and
- getter.
Note: New attributes cannot be added using this interface. New attributes must be added using addAttr, or an appropriate manner for a class which utilises Attributes (e.g. the ATTRS property in Base).
on
-
type
-
fn
-
[context]
-
[arg*]
Subscribe a callback function to a custom event fired by this object or from an object that bubbles its events to this object.
this.on("change", this._onChange, this);
Callback functions for events published with emitFacade = true
will
receive an EventFacade
as the first argument (typically named "e").
These callbacks can then call e.preventDefault()
to disable the
behavior published to that event's defaultFn
. See the EventFacade
API for all available properties and methods. Subscribers to
non-emitFacade
events will receive the arguments passed to fire()
after the event name.
To subscribe to multiple events at once, pass an object as the first argument, where the key:value pairs correspond to the eventName:callback.
this.on({
"attrChange" : this._onAttrChange,
"change" : this._onChange
});
You can also pass an array of event names as the first argument to subscribe to all listed events with the same callback.
this.on([ "change", "attrChange" ], this._onChange);
Returning false
from a callback is supported as an alternative to
calling e.preventDefault(); e.stopPropagation();
. However, it is
recommended to use the event methods whenever possible.
Parameters:
Returns:
A subscription handle capable of detaching that subscription
once
-
type
-
fn
-
[context]
-
[arg*]
Listen to a custom event hosted by this object one time.
This is the equivalent to on
except the
listener is immediatelly detached when it is executed.
Parameters:
Returns:
A subscription handle capable of detaching the subscription
onceAfter
-
type
-
fn
-
[context]
-
[arg*]
Listen to a custom event hosted by this object one time.
This is the equivalent to after
except the
listener is immediatelly detached when it is executed.
Parameters:
Returns:
A subscription handle capable of detaching that subscription
parse
-
response
Called to parse the response when the model is loaded from the server. This method receives a server response and is expected to return an attribute hash.
The default implementation assumes that response is either an attribute
hash or a JSON string that can be parsed into an attribute hash. If
response is a JSON string and either Y.JSON
or the native JSON
object
are available, it will be parsed automatically. If a parse error occurs, an
error
event will be fired and the model will not be updated.
You may override this method to implement custom parsing logic if necessary.
Parameters:
-
response
AnyServer response.
Returns:
Attribute hash.
parseType
-
type
-
[pre]
Takes the type parameter passed to 'on' and parses out the various pieces that could be included in the type. If the event type is passed without a prefix, it will be expanded to include the prefix one is supplied or the event target is configured with a default prefix.
Parameters:
Returns:
an array containing:
- the detach category, if supplied,
- the prefixed event type,
- whether or not this is an after listener,
- the supplied event type
publish
-
type
-
opts
Creates a new custom event of the specified type. If a custom event by that name already exists, it will not be re-created. In either case the custom event is returned.
Parameters:
-
type
Stringthe type, or name of the event
-
opts
Objectoptional config params. Valid properties are:
-
[broadcast=false]
Boolean optionalwhether or not the YUI instance and YUI global are notified when the event is fired.
-
[bubbles=true]
Boolean optionalWhether or not this event bubbles. Events can only bubble if
emitFacade
is true. -
[context=this]
Object optionalthe default execution context for the listeners.
-
[defaultFn]
Function optionalthe default function to execute when this event fires if preventDefault was not called.
-
[emitFacade=false]
Boolean optionalwhether or not this event emits a facade.
-
[prefix]
String optionalthe prefix for this targets events, e.g., 'menu' in 'menu:click'.
-
[fireOnce=false]
Boolean optionalif an event is configured to fire once, new subscribers after the fire will be notified immediately.
-
[async=false]
Boolean optionalfireOnce event listeners will fire synchronously if the event has already fired unless
async
istrue
. -
[preventable=true]
Boolean optionalwhether or not
preventDefault()
has an effect. -
[preventedFn]
Function optionala function that is executed when
preventDefault()
is called. -
[queuable=false]
Boolean optionalwhether or not this event can be queued during bubbling.
-
[silent]
Boolean optionalif silent is true, debug messages are not provided for this event.
-
[stoppedFn]
Function optionala function that is executed when stopPropagation is called.
-
[monitored]
Boolean optionalspecifies whether or not this event should send notifications about when the event has been attached, detached, or published.
-
[type]
String optionalthe event type (valid option if not provided as the first parameter to publish).
-
Returns:
the custom event
removeAttr
-
name
Removes an attribute from the host object
Parameters:
-
name
StringThe name of the attribute to be removed.
reset
-
name
Resets the attribute (or all attributes) to its initial value, as long as the attribute is not readOnly, or writeOnce.
Parameters:
-
name
StringOptional. The name of the attribute to reset. If omitted, all attributes are reset.
Returns:
A reference to the host object.
save
-
[options]
-
[callback]
Saves this model to the server.
This method delegates to the sync()
method to perform the actual save
operation, which is an asynchronous action. Specify a callback function to
be notified of success or failure.
A successful save operation will fire a save
event, while an unsuccessful
save operation will fire an error
event with the src
value "save".
If the save operation succeeds and one or more of the attributes returned in
the server's response differ from this model's current attributes, a
change
event will be fired.
Parameters:
-
[options]
Object optionalOptions to be passed to
sync()
and toset()
when setting synced attributes. It's up to the custom sync implementation to determine what options it supports or requires, if any. -
[callback]
Function optionalCalled when the sync operation finishes.
-
err
Error | NullIf an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, err will be
null
. -
response
AnyThe server's response. This value will be passed to the
parse()
method, which is expected to parse it and return an attribute hash.
-
set
-
name
-
value
-
[options]
Sets the value of a single attribute. If model validation fails, the
attribute will not be set and an error
event will be fired.
Use setAttrs()
to set multiple attributes at once.
Parameters:
Example:
model.set('foo', 'bar');
setAttrs
-
attributes
-
[options]
Sets the values of multiple attributes at once. If model validation fails,
the attributes will not be set and an error
event will be fired.
Parameters:
Example:
model.setAttrs({
foo: 'bar',
baz: 'quux'
});
subscribe
()
deprecated
subscribe to an event
sync
-
action
-
[options]
-
[callback]
Override this method to provide a custom persistence implementation for this model. The default just calls the callback without actually doing anything.
This method is called internally by load()
, save()
, and destroy()
, and
their implementations rely on the callback being called. This effectively
means that when a callback is provided, it must be called at some point for
the class to operate correctly.
Parameters:
-
action
StringSync action to perform. May be one of the following:
-
create
: Store a newly-created model for the first time. -
delete
: Delete an existing model. -
read
: Load an existing model. -
update
: Update an existing model.
-
-
[options]
Object optionalSync options. It's up to the custom sync implementation to determine what options it supports or requires, if any.
-
[callback]
Function optionalCalled when the sync operation finishes.
-
err
Error | NullIf an error occurred, this parameter will contain the error. If the sync operation succeeded, err will be falsy.
-
[response]
Any optionalThe server's response.
-
toJSON
()
Object
Returns a copy of this model's attributes that can be passed to
Y.JSON.stringify()
or used for other nefarious purposes.
The clientId
attribute is not included in the returned object.
If you've specified a custom attribute name in the idAttribute
property,
the default id
attribute will not be included in the returned object.
Note: The ECMAScript 5 specification states that objects may implement a
toJSON
method to provide an alternate object representation to serialize
when passed to JSON.stringify(obj)
. This allows class instances to be
serialized as if they were plain objects. This is why Model's toJSON
returns an object, not a JSON string.
See http://es5.github.com/#x15.12.3 for details.
Returns:
Copy of this model's attributes.
toString
()
String
Default toString implementation. Provides the constructor NAME and the instance guid, if set.
Returns:
String representation for this object
undo
-
[attrNames]
-
[options]
Reverts the last change to the model.
If an attrNames array is provided, then only the named attributes will be reverted (and only if they were modified in the previous change). If no attrNames array is provided, then all changed attributes will be reverted to their previous values.
Note that only one level of undo is available: from the current state to the
previous state. If undo()
is called when no previous state is available,
it will simply do nothing.
Parameters:
-
[attrNames]
String[] optionalArray of specific attribute names to revert. If not specified, all attributes modified in the last change will be reverted.
-
[options]
Object optionalData to be mixed into the event facade of the change event(s) for these attributes.
-
[silent=false]
Boolean optionalIf
true
, nochange
event will be fired.
-
unsubscribe
()
deprecated
detach a listener
unsubscribeAll
-
type
Removes all listeners from the specified event. If the event type is not specified, all listeners from all hosted custom events will be removed.
Parameters:
-
type
StringThe type, or name of the event
validate
-
attrs
-
callback
Override this method to provide custom validation logic for this model.
While attribute-specific validators can be used to validate individual
attributes, this method gives you a hook to validate a hash of all
attributes before the model is saved. This method is called automatically
before save()
takes any action. If validation fails, the save()
call
will be aborted.
In your validation method, call the provided callback
function with no
arguments to indicate success. To indicate failure, pass a single argument,
which may contain an error message, an array of error messages, or any other
value. This value will be passed along to the error
event.
Parameters:
-
attrs
ObjectAttribute hash containing all model attributes to be validated.
-
callback
FunctionValidation callback. Call this function when your validation logic finishes. To trigger a validation failure, pass any value as the first argument to the callback (ideally a meaningful validation error of some kind).
-
[err]
Any optionalValidation error. Don't provide this argument if validation succeeds. If validation fails, set this to an error message or some other meaningful value. It will be passed along to the resulting
error
event.
-
Example:
model.validate = function (attrs, callback) {
if (attrs.pie !== true) {
// No pie?! Invalid!
callback('Must provide pie.');
return;
}
// Success!
callback();
};
Properties
changed
Object
Hash of attributes that have changed since the last time this model was saved.
Default: {}
idAttribute
String
Name of the attribute to use as the unique id (or primary key) for this model.
The default is id
, but if your persistence layer uses a different name for
the primary key (such as _id
or uid
), you can specify that here.
The built-in id
attribute will always be an alias for whatever attribute
name you specify here, so getting and setting id
will always behave the
same as getting and setting your custom id attribute.
Default: `'id'`
lastChange
Object
Hash of attributes that were changed in the last change
event. Each item
in this hash is an object with the following properties:
-
newVal
: The new value of the attribute after it changed. -
prevVal
: The old value of the attribute before it changed. -
src
: The source of the change, ornull
if no source was specified.
Default: {}
lists
ModelList[]
Array of ModelList
instances that contain this model.
When a model is in one or more lists, the model's events will bubble up to those lists. You can subscribe to a model event on a list to be notified when any model in the list fires that event.
This property is updated automatically when this model is added to or
removed from a ModelList
instance. You shouldn't alter it manually. When
working with models in a list, you should always add and remove models using
the list's add()
and remove()
methods.
Default: `[]`
Example:
Subscribing to model events on a list:
// Assuming list
is an existing Y.ModelList instance.
list.on('*:change', function (e) {
// This function will be called whenever any model in the list
// fires a change
event.
//
// e.target
will refer to the model instance that fired the
// event.
});
Attributes
clientId
String
readonly
A client-only identifier for this model.
Like the id
attribute, clientId
may be used to retrieve model
instances from lists. Unlike the id
attribute, clientId
is
automatically generated, and is only intended to be used on the client
during the current pageview.
Fires event clientIdChange
Fires when the value for the configuration attribute clientId
is
changed. You can listen for the event using the on
method if you
wish to be notified before the attribute's value has changed, or
using the after
method if you wish to be notified after the
attribute's value has changed.
Parameters:
-
e
EventFacadeAn Event Facade object with the following attribute-specific properties added:
destroyed
Boolean
readonly
Flag indicating whether or not this object has been through the destroy lifecycle phase.
Default: false
Fires event destroyedChange
Fires when the value for the configuration attribute destroyed
is
changed. You can listen for the event using the on
method if you
wish to be notified before the attribute's value has changed, or
using the after
method if you wish to be notified after the
attribute's value has changed.
Parameters:
-
e
EventFacadeAn Event Facade object with the following attribute-specific properties added:
id
String | Number | Null
A unique identifier for this model. Among other things, this id may be used to retrieve model instances from lists, so it should be unique.
If the id is empty, this model instance is assumed to represent a new item that hasn't yet been saved.
If you would prefer to use a custom attribute as this model's id instead
of using the id
attribute (for example, maybe you'd rather use _id
or uid
as the primary id), you may set the idAttribute
property to
the name of your custom id attribute. The id
attribute will then
act as an alias for your custom attribute.
Default: `null`
Fires event idChange
Fires when the value for the configuration attribute id
is
changed. You can listen for the event using the on
method if you
wish to be notified before the attribute's value has changed, or
using the after
method if you wish to be notified after the
attribute's value has changed.
Parameters:
-
e
EventFacadeAn Event Facade object with the following attribute-specific properties added:
initialized
Boolean
readonly
Flag indicating whether or not this object has been through the init lifecycle phase.
Default: false
Fires event initializedChange
Fires when the value for the configuration attribute initialized
is
changed. You can listen for the event using the on
method if you
wish to be notified before the attribute's value has changed, or
using the after
method if you wish to be notified after the
attribute's value has changed.
Parameters:
-
e
EventFacadeAn Event Facade object with the following attribute-specific properties added:
Events
change
Fired when one or more attributes on this model are changed.
destroy
Lifecycle event for the destroy phase, fired prior to destruction. Invoking the preventDefault method on the event object provided to subscribers will prevent destruction from proceeding.
Subscribers to the "after" moment of this event, will be notified after destruction is complete (and as a result cannot prevent destruction).
Event Payload:
-
e
EventFacadeEvent object
error
Fired when an error occurs, such as when the model doesn't validate or when a sync layer response can't be parsed.
Event Payload:
-
error
AnyError message, object, or exception generated by the error. Calling
toString()
on this should result in a meaningful error message. -
src
StringSource of the error. May be one of the following (or any custom error source defined by a Model subclass):
-
load
: An error loading the model from a sync layer. The sync layer's response (if any) will be provided as theresponse
property on the event facade. -
parse
: An error parsing a JSON response. The response in question will be provided as theresponse
property on the event facade. -
save
: An error saving the model to a sync layer. The sync layer's response (if any) will be provided as theresponse
property on the event facade. -
validate
: The model failed to validate. The attributes being validated will be provided as theattributes
property on the event facade.
-
init
Lifecycle event for the init phase, fired prior to initialization. Invoking the preventDefault() method on the event object provided to subscribers will prevent initialization from occuring.
Subscribers to the "after" momemt of this event, will be notified after initialization of the object is complete (and therefore cannot prevent initialization).
Event Payload:
-
e
EventFacadeEvent object, with a cfg property which refers to the configuration object passed to the constructor.
load
Fired after model attributes are loaded from a sync layer.
Event Payload:
-
parsed
ObjectThe parsed version of the sync layer's response to the load request.
-
response
AnyThe sync layer's raw, unparsed response to the load request.
save
Fired after model attributes are saved to a sync layer.
Event Payload:
-
[parsed]
Object optionalThe parsed version of the sync layer's response to the save request, if there was a response.
-
[response]
Any optionalThe sync layer's raw, unparsed response to the save request, if there was one.