Model is a lightweight Attribute-based data model with methods for getting, setting, validating, and syncing attribute values to a persistence layer or server, as well as events for notifying listeners of model changes.
The Y.Model
class is intended to be extended by a custom class that defines
custom model attributes, validators, and behaviors.
Getting Started
To include the source files for Model and its dependencies, first load the YUI seed file if you haven't already loaded it.
<script src="http://yui.yahooapis.com/3.11.0/build/yui/yui-min.js"></script>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the YUI().use()
method.
YUI will automatically load any dependencies required by the modules you
specify.
<script> // Create a new YUI instance and populate it with the required modules. YUI().use('model', function (Y) { // Model is available and ready for use. Add implementation // code here. }); </script>
For more information on creating YUI instances and on the
use()
method, see the
documentation for the YUI Global Object.
What is a Model?
A model is a class that manages data, state, and behavior associated with an application or a part of an application.
For example, in a photo gallery, you might use a model to represent each photo. The model would contain information about the image file, a caption, tags, etc., along with methods for working with this data. The model would also be responsible for validating any new data before accepting it.
While Model may be used as a standalone component, it's common to associate a Model instance with a View instance, which is responsible for rendering the visual representation of the data contained in the model and updating that representation when the model changes.
Using Model
Quick Start
The quickest way to get up and running with Model is to create a new instance of the Y.Model
class and pass in an object of key/value pairs representing attributes to set (note: creating ad-hoc attributes like this requires YUI 3.5.0 or higher).
Here's how you might create a simple model representing a delicious pie (imagine you're building an online ordering system for a bakery):
var applePie = new Y.Model({ slices: 6, // number of slices in this pie type : 'apple' // what type of pie this is });
This creates a new Y.Model
instance named applePie
, with two attributes: slices
and type
, in addition to the built-in attributes id
and clientId
, which are available on all models.
Pass the name of an attribute to the model's get()
function to get that attribute's value.
applePie.get('slices'); // => 6 applePie.get('type'); // => "apple"
To change the value of an attribute, pass its name and new value to set()
.
applePie.set('slices', 5); // someone ate a slice!
Read on to learn how to create custom model subclasses for representing more complex data and logic, or skip ahead to Model Events or Getting and Setting Attribute Values to learn more about how to take advantage of the useful state management functionality Model provides.
Extending Y.Model
The ability to create ad-hoc models by instantiating Y.Model
is convenient, but sometimes it can be useful to create a custom Model subclass by extending Y.Model
. This allows you to declare the data attributes your Model class will manage up front, as well as specify default attribute values, helper methods, validators, and (optionally) a sync layer to help your Model class communicate with a storage API or a remote server.
In this example, we'll create a Y.PieModel
class. Each instance of this class will represent a delicious pie, fresh from the oven.
// Create a new Y.PieModel class that extends Y.Model. Y.PieModel = Y.Base.create('pieModel', Y.Model, [], { // Add prototype methods for your Model here if desired. These methods will be // available to all instances of your Model. // Returns true if all the slices of the pie have been eaten. allGone: function () { return this.get('slices') === 0; }, // Consumes a slice of pie, or fires an `error` event if there are no slices // left. eatSlice: function () { if (this.allGone()) { this.fire('error', { type : 'eat', error: "Oh snap! There isn't any pie left." }); } else { this.set('slices', this.get('slices') - 1); Y.log('You just ate a slice of delicious ' + this.get('type') + ' pie!'); } } }, { ATTRS: { // Add custom model attributes here. These attributes will contain your // model's data. See the docs for Y.Attribute to learn more about defining // attributes. slices: { value: 6 // default value }, type: { value: 'apple' } } });
Now we can create instances of Y.PieModel
to represent delicious pies.
Each instance will have a type
attribute containing the type of the pie and a slices
attribute containing the number of slices remaining. We can call the allGone()
method to check whether there are any slices left, and the eatSlice()
method to eat a slice.
// Bake a delicious new pecan pie. var pecanPie = new Y.PieModel({type: 'pecan'}); pecanPie.on('error', function (e) { Y.log(e.error); }); pecanPie.eatSlice(); // => "You just ate a slice of delicious pecan pie!" Y.log(pecanPie.get('slices')); // => 5
Five slices later, our pie will be all gone. If we try to eat another slice, we'll get an error
event.
// 5 slices later... pecanPie.eatSlice(); // => "Oh snap! There isn't any pie left."
Model Attributes
A Model's data is represented by attributes. The Model class provides two built-in attributes, clientId
and id
. The rest are up to you to define when you extend Y.Model
.
Built-in Attributes
Attribute | Default Value | Description |
---|---|---|
clientId |
generated id |
An automatically generated client-side only unique ID for identifying model instances that don't yet have an |
id |
null |
A globally unique identifier for the model instance. If this is
If your persistence layer uses a primary key with a name other than |
Custom Attributes
Custom attributes are where all your model's data should live. You define these attributes when you first extend Y.Model
. You can set their values by passing a config object into the model's constructor, or by calling the model's set()
or setAttrs()
methods..
Attributes can specify default values, getters and setters, validators, and more. For details, see the documentation for the Attribute component.
Model Properties
The following properties are available on Model instances. The idAttribute
property may be overridden when extending Y.Model
; the others are intended to be read-only.
Property | Type | Description |
---|---|---|
changed |
Object |
Hash of attributes that have changed since the last time the model was saved. |
idAttribute |
String |
Name of the attribute to use as the unique id for the model. Defaults to "id", but you may override this property when extending |
lastChange |
Object |
Hash of attributes that were changed in the most recent
|
lists |
Array |
Array of ModelList instances that contain this model.
This property is updated automatically when the 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 |
Model Events
Model instances provide the following events:
Event | When | Payload |
---|---|---|
change |
One or more attributes on the model are changed. |
|
error |
An error occurs, such as when the model fails validation or a sync layer response can't be parsed. |
|
load |
After model attributes are loaded from a sync layer. |
|
save |
After model attributes are saved to a sync layer. |
|
A model's events bubble up to any model lists that the model belongs to. This enables you to use the model list as a central point for handling model value changes and errors.
Change Events
In addition to the master change
event, which is fired whenever one or more attributes are changed, there are also change events for each individual attribute.
Attribute-level change events follow the naming scheme nameChange
, where name is the name of an attribute.
// Bake a new pie model. var pie = new Y.PieModel(); // Listen for all attribute changes. pie.on('change', function (e) { Y.log('change fired: ' + Y.Object.keys(e.changed).join(', ')); }); // Listen for changes to the `slices` attribute. pie.on('slicesChange', function (e) { Y.log('slicesChange fired'); }); // Listen for changes to the `type` attribute. pie.on('typeChange', function (e) { Y.log('typeChange fired'); }); // Change multiple attributes at once. pie.setAttrs({ slices: 3, type : 'maple custard' }); // => "slicesChange fired" // => "typeChange fired" // => "change fired: slices, type"
Firing Your Own Error Events
In your custom model class, there may be situations beyond just parsing and validating in which an error
event would be useful. For example, in the Y.PieModel
class, we fire an error when someone tries to eat a slice of pie and there are no slices left.
// Consumes a slice of pie, or fires an `error` event if there are no slices // left. eatSlice: function () { if (this.allGone()) { this.fire('error', { type : 'eat', error: "Oh snap! There isn't any pie left." }); } else { this.set('slices', this.get('slices') - 1); Y.log('You just ate a slice of delicious ' + this.get('type') + ' pie!'); } }
When firing an error event, set the type
property to something that users of your class can use to identify the type of error that has occurred. In the example above, we set it to "eat", because it occurred when the caller tried to eat a slice of pie.
The error
property should be set to an error message, an Error object, or anything else that provides information about the error and has a toString()
method that returns an error message string.
Working with Model Data
Getting and Setting Attribute Values
Model's get()
and set()
methods are the main ways of interacting with model attributes. Unsurprisingly, they allow you to get and set the value of a single attribute.
var pie = new Y.PieModel(); // Set the value of the `type` attribute. pie.set('type', 'banana cream'); // Get the value of the `type` attribute. pie.get('type'); // => "banana cream"
Model also provides two convenience methods for getting and escaping an attribute value in a single step. The getAsHTML()
method returns an HTML-escaped value, and the getAsURL()
method returns a URL-encoded value.
pie.set('type', 'strawberries & cream'); pie.getAsHTML('type'); // => "strawberries & cream" pie.getAsURL('type'); // => "strawberries%20%26%20cream"
The getAttrs()
and setAttrs()
methods may be used to get and set multiple attributes at once. getAttrs()
returns a hash of all attribute values, while setAttrs()
accepts a hash of attribute values. When you set multiple attributes with setAttrs()
, it fires only a single change event that contains all the affected attributes..
pie.setAttrs({ slices: 6, type : 'marionberry' }); pie.getAttrs(); // => { // clientId: "pieModel_1", // destroyed: false, // id: null, // initialized: true, // slices: 6, // type: "marionberry" // }
The destroyed
and initialized
attributes you see in the sample output above are lifecycle attributes provided by Y.Base
, and aren't actually model data.
To get a slightly more useful representation of model data, use the toJSON()
method. The toJSON()
method excludes the clientId
, destroyed
, and initialized
attributes, making the resulting object more suitable for serialization and for storing in a persistence layer.
pie.toJSON(); // => { // id: null, // slices: 6, // type: "marionberry" // }
If a custom idAttribute
is in use, the toJSON()
output will include that id attribute instead of id
.
// toJSON() output with a custom id attribute. pie.toJSON(); // => { // customId: null, // slices: 6, // type: "marionberry" // }
If you'd like to customize the serialized representation of your models, you may override the toJSON()
method.
When using the set()
and setAttrs()
methods, you may pass an optional options
argument. If options.silent
is true
, no change
event will be fired.
// Set attributes without firing a `change` event. pie.set('slices', 0, {silent: true}); pie.setAttrs({ slices: 0, type : 'chocolate cream' }, {silent: true});
After making changes to a model's attributes, you may call the undo()
method to undo the previous change.
var pie = new Y.PieModel({slices: 6}); pie.set('slices', 5); pie.undo(); pie.get('slices'); // => 6
Note that there's only a single level of undo, so it's not possible to revert past the most recent change.
Validating Changes
Validating model changes as they occur is a good way to ensure that the data in your models isn't nonsense, especially when dealing with user input.
There are two ways to validate model attributes. One way is to define an attribute validator function for an individual attribute when you extend Y.Model
.
// Defining an individual attribute validator. Y.PieModel = Y.Base.create('pieModel', Y.Model, [], { // ... prototype methods and properties ... }, { ATTRS: { slices: { value: 6, validator: function (value) { return typeof value === 'number' && value >= 0 && value <= 10; } }, // ... } });
An attribute validator will be called whenever that attribute changes, and can prevent the change from taking effect by returning false
. Model error
events are not fired when attribute validators fail. For more details on attribute validators, see the Attribute User Guide.
The second way to validate changes is to provide a custom validate()
method when extending Y.Model
. The validate()
method will be called automatically when save()
is called, and will receive a hash of all the attributes in the model. Validation can be an asyncronous process, and the validation()
method takes a callback()
function. If your validate()
method calls the callback()
with an argument other than null
, or undefined
, it will be considered a validation failure, an error
event will be fired with the returned value as the error message, and the save()
action will be aborted.
To indicate success, call the provided callback()
function with no arguments from your validation method. To indicate failure, call the provided callback()
function with a single argument, which may contain an error message, an array of error messages, or any other value. On validation failure an error
event will be fired with the passed argument as the error message.
// Defining a model-wide `validator()` method. Y.PieModel = Y.Base.create('pieModel', Y.Model, [], { // ... prototype methods and properties ... validate: function (attributes, callback) { var slices; switch (attributes.type) { case 'rhubarb': callback('Eww. No. Not allowed.'); return; case 'maple custard': slices = Y.Lang.isValue(attributes.slices) ? attributes.slices : this.get('slices'); if (slices < 10) { callback("Making fewer than 10 slices of maple custard pie would be " + "silly, because I'm just going to eat 8 of them as soon as it's " + "out of the oven."); return; } } // Success! callback(); } }, { // ... attributes ... });
Loading and Saving Model Data
Calling a model's load()
and save()
methods will result in a behind-the-scenes call to the model's sync()
method specifying the appropriate action.
The default sync()
method does nothing, but by overriding it and providing your own sync layer, you can make it possible to create, read, update, and delete models from a persistence layer or a server. See Implementing a Model Sync Layer for more details.
The load()
and save()
methods each accept two optional parameters: an options object and a callback function. If provided, the options object will be passed to the sync layer, and the callback will be called after the load or save operation is finished. You may provide neither parameter, or just an options object, or just a callback, although if you provide both an options object and a callback, they need to be in that order.
The callback function will receive two parameters: an error (this parameter will be null
or undefined
if the operation was successful) and a response (which is the result of calling the model's parse()
method with whatever response the sync layer returned).
The load()
method calls sync()
with the read
action, and automatically updates the model with the response data (by passing it to parse()
and then updating attributes based on the hash that parse()
returns) before calling the callback.
var pie = new Y.PieModel({id: 'pie123'}); // Load a pie model, passing a callback that will run when the model has // been loaded. pie.load(function (err, response) { if (!err) { // Success! The model now contains the loaded data. } });
The save()
method will do one of two things: if the model is new (meaning it doesn't yet have an id
value), it will call sync()
with the "create" action. If the model is not new, then it will call sync()
with the "update" action.
If the sync layer returns a response, then save()
will update the model's attributes with the response data before calling the callback function.
// Save a pie model, passing a callback that will run when the model has // been saved. pie.save(function (err, response) { if (!err) { // Success! The model has been saved. If the sync layer returned a response, // then the model has also been updated with any new data in the response. } });
In addition to calling the specified callback (if any), the load()
and save()
methods will fire a load
event and a save
event respectively on success, or an error
event on failure. See Model Events for more details on these events.
Always use the load()
or save()
methods rather than calling sync()
directly, since this ensures that the sync layer's response is passed through the parse()
method and that the model's data is updated if necessary.
The Model Lifecycle
When a model is first created and doesn't yet have an id
value, it's considered "new". The isNew()
method will tell you whether or not a model is new.
Once a model has an id
value, either because one was manually set or because the model received one when it was loaded or saved, the model is no longer considered new, since it is assumed to exist in a persistence layer or on a server somewhere.
If a model is new or if any of its attributes have changed since the model was last loaded or saved, the model is considered "modified". The isModified()
method will tell you whether or not a model is modified. A successful call to load()
or save()
will reset a model's "modified" flag.
Finally, a model's destroy()
method can be used to destroy the model instance. Calling destroy()
with no arguments will destroy only the local model instance, while calling destroy({remove: true})
will both destroy the local model instance and call the sync layer with the "delete" action to delete the model from a persistence layer or server.
It's not necessary for a model to support all possible sync actions. A model that's used to represent read-only data might use a sync layer that only implements the read
action, for instance. In this case, the other actions should simply be no-ops that either call the sync callback immediately, or pass an error to the sync callback indicating that the action isn't supported (depending on your personal preference).
Model Sync Layers
A model's save()
, load()
, and destroy()
methods all internally call the model's sync()
method to carry out an action. The default sync()
method doesn't actually do anything, but you can mix one of the following sync layers into your Y.Model
/Y.ModelList
subclass or implement a custom sync layer.
RESTful XHR
Y.ModelSync.REST
is an extension which provides a RESTful XHR sync()
implementation that can be mixed into a Model or ModelList subclass.
This makes it trivial for your Model or ModelList subclasses communicate and transmit their data via RESTful XHR. In most cases you'll only need to provide a value for root
when sub-classing Y.Model
.
// Create `Y.User`, a `Y.Model` subclass and mix-in the RESTful XHR sync layer. Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], { // The root or collection path segment for the server's Users resource. root: '/users' }); var existingUser = new Y.User({id: '1'}), oldUser = new Y.User({id: '2'}), newUser = new Y.User({name: 'Eric Ferraiuolo'}); // GET the existing user data from: "/users/1" existingUser.load(function () { Y.log(existingUser.get('name')); // => "Ron Swannson" // Correct the user's `name` and PUT the updated user at: "/users/1" existingUser.set('name', 'Ron Swanson').save(); }); // DELETE the old user data at: "/users/2" oldUser.destroy({remove: true}); // POST the new user data to: "/users" newUser.save(function () { // The server can return the user data with an `id` assigned. Y.log(newUser.get('id')); // => "3" });
The following sections provide details on how to use and configure the Y.ModelSync.REST
extension. You can also refer to the API docs for more information.
Configuring URLs
In order for this sync layer to make requests to a server it needs a URL. Some useful conventions have been put in place to generate these URLs, thus reducing the amount of configuration required to use this sync layer.
The url
property works in conjunction with the root
property to generate the URLs needed to make the XHRs. By simply configuring a root
on the prototype of your Model subclass to the URL of collection resource on the server, your model's and model lists' URLs can be automatically generated. The following example sets up a Model and ModelList subclass and configures them to work with this sync layer:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], { root: '/users' }); Y.Users = Y.Base.create('users', Y.ModelList, [Y.ModelSync.REST], { // By convention `Y.User`'s `root` will be used for the lists' URL. model: Y.User }); var users = new Y.Users(); // GET users list from: "/users" users.load(function () { var firstUser = users.item(0); Y.log(firstUser.get('id')); // => "1" // PUT updated user data at: "/users/1" firstUser.set('name', 'Eric').save(); });
By convention, the URL generated for a model when preforming a read, update, or delete action will combine with the configured root
with the model's id
. When creating the model resource on the server, just the root
will be used as the URL.
Note: If the root
string ends in trailing-slash, the generated URLs will also end with a "/", and if the root
does not end with a slash, neither will the generated URLs.
If a url
is specified, it will be processed by Y.Lang.sub()
, which is useful when the URLs for a Model/ModelList subclass match a specific pattern and can use simple replacement tokens; e.g.:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], { root: '/users', url : '/users/{username}' });
Note: String subsitituion of the url
only use string an number values provided by this object's attribute and/or the options
passed to the getURL()
method. Do not expect something fancy to happen with Object, Array, or Boolean values, they will simply be ignored.
For more details, refer to the API docs for the root
and url
properties, and the getURL()
method.
Authentic Requests
Anytime a server accepts requests from clients which result in state being changed, the server is susceptible to Cross-Site Request Forgery (CSRF) attacks. This extension has build in support for authenticity tokens to help prevent these CSRF attacks.
A CSRF token provided by the server can be embedded in the HTML document and assigned to YUI.Env.CSRF_TOKEN
like this:
<script> YUI.Env.CSRF_TOKEN = {{session.authenticityToken}}; </script>
The above should come after YUI seed file so that YUI.Env
will be defined.
Note: This can be overridden on a per-request basis. See sync()
method.
When a value for the CSRF token is provided, either statically or via options
passed to the save()
and destroy()
methods, the applicable HTTP requests will have a X-CSRF-Token
header added with the token value.
Overriding HTTP Defaults
If the server-side HTTP framework isn't RESTful, setting the static Y.ModelSync.REST.EMULATE_HTTP
flag to true
will cause all PUT and DELETE requests to instead use the POST HTTP method, and add a X-HTTP-Method-Override
HTTP header with the value of the method type which was overridden.
Additionally, the mapping of CRUD actions to HTTP methods can be changed. By default, the static mapping provided by Y.ModelSync.REST.HTTP_METHODS
is:
CRUD Action | HTTP Method | Description |
---|---|---|
create |
POST |
Creates a new resource on the server for the model. |
read |
GET |
Loads the data for a model from its resource on the server. |
update |
PUT |
Updates the resource on the server with the new model data. |
delete |
DELETE |
Removes the resource for the model from the server. |
Content-Types Other Than JSON
By default, this extension will communicate with the server using JSON, by setting the Accept
and Content-Type
HTTP headers for all XHRs to "application/json", it signals the server to process the request bodies as JSON and send JSON responses.
If you're sending and receiving content other than JSON, you can override these default headers on the static Y.ModelSync.REST.HTTP_HEADERS
object. Additionally, you'll want to provide custom implementations of your Model subclass' parse()
and serialize()
methods. The serialize()
method is added by this extension, by default it JSON-stringifies to result of calling the model's toJSON()
method.
For more information on the Y.ModelSync.REST
extension, refer to its API docs.
Implementing a Model Sync Layer
A sync layer might make Ajax requests to a remote server, or it might act as a wrapper around local storage, or any number of other things. By overriding the sync()
method, you can provide a custom sync layer.
The sync()
Method
When the sync()
method is called, it receives three arguments:
action
(String)-
A string that indicates the intended sync action. May be one of the following values:
create
-
Create a new model record. The "create" action occurs when a model is saved and doesn't yet have an
id
value. read
-
Read an existing model record. The record should be identified based on the
id
attribute of the model. update
-
Update an existing model record. The "update" action occurs when a model is saved and already has an
id
value. The record to be updated should be identified based on theid
attribute of the model. delete
-
Delete an existing model record. The record to be deleted should be identified based on the
id
attribute of the model.
options
(Object)-
A hash containing any options that were passed to the
save()
,load()
ordestroy()
method. This may be used to pass custom options to a sync layer. callback
(Function)-
A callback function that should be called when the sync operation is complete. The callback expects to receive the following arguments:
err
-
Error message or object if an error occured,
null
orundefined
if the operation was successful. response
-
Response from the persistence layer, if any. This will be passed to the
parse()
method to be parsed.
Implementing a sync layer is as simple as handling the requested sync action and then calling the callback function. Here's a sample sync layer that stores records in local storage (note: this example requires the json-stringify
module):
Y.PieModel = Y.Base.create('pieModel', Y.Model, [], { // ... prototype methods and properties ... // Custom sync layer. sync: function (action, options, callback) { var data; switch (action) { case 'create': data = this.toJSON(); // Use the current timestamp as an id just to simplify the example. In a // real sync layer, you'd want to generate an id that's more likely to // be globally unique. data.id = Y.Lang.now(); // Store the new record in localStorage, then call the callback. localStorage.setItem(data.id, Y.JSON.stringify(data)); callback(null, data); return; case 'read': // Look for an item in localStorage with this model's id. data = localStorage.getItem(this.get('id')); if (data) { callback(null, data); } else { callback('Model not found.'); } return; case 'update': data = this.toJSON(); // Update the record in localStorage, then call the callback. localStorage.setItem(this.get('id'), Y.JSON.stringify(data)); callback(null, data); return; case 'delete': localStorage.removeItem(this.get('id')); callback(); return; default: callback('Invalid action'); } } }, { // ... attributes ... });
The parse()
Method
Depending on the kind of response your sync layer returns, you may need to override the parse()
method as well. The default parse()
implementation knows how to parse JavaScript objects and JSON strings that can be parsed into JavaScript objects representing a hash of attributes. If your response data is in another format, such as a nested JSON response or XML, override the parse()
method to provide a custom parser implementation.
If an error occurs while parsing a response, fire an error
event with type
"parse".
This sample demonstrates a custom parser for responses in which the model data is contained in a data
property of the response object.
// Custom response parser. parse: function (response) { if (response.data) { return response.data; } this.fire('error', { type : 'parse', error: 'No data in the response.' }); }