6
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700">
7
<link rel="stylesheet" href="../../build/cssgrids/grids-min.css">
8
<link rel="stylesheet" href="../assets/css/main.css">
9
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
10
<script src="../../build/yui/yui-min.js"></script>
18
<a href="#toc" class="jump">Jump to Table of Contents</a>
22
<div class="yui3-u-3-4">
24
<div class="content"><div class="intro">
26
Model is a lightweight <a href="../attribute/index.html">Attribute</a>-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.
30
The <code>Y.Model</code> class is intended to be extended by a custom class that defines
31
custom model attributes, validators, and behaviors.
35
<h2 id="getting-started">Getting Started</h2>
38
To include the source files for Model and its dependencies, first load
39
the YUI seed file if you haven't already loaded it.
42
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js"></script></pre>
46
Next, create a new YUI instance for your application and populate it with the
47
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
48
YUI will automatically load any dependencies required by the modules you
52
<pre class="code prettyprint"><script>
53
// Create a new YUI instance and populate it with the required modules.
54
YUI().use('model', function (Y) {
55
// Model is available and ready for use. Add implementation
56
// code here.
58
</script></pre>
62
For more information on creating YUI instances and on the
63
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
64
documentation for the <a href="../yui/index.html">YUI Global Object</a>.
68
<h2 id="what-is-a-model">What is a Model?</h2>
71
A model is a class that manages data, state, and behavior associated with an application or a part of an application.
75
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.
79
While Model may be used as a standalone component, it's common to associate a Model instance with a <a href="../view/index.html">View</a> instance, which is responsible for rendering the visual representation of the data contained in the model and updating that representation when the model changes.
82
<h2 id="using-model">Using Model</h2>
84
<h3 id="quick-start">Quick Start</h3>
87
The quickest way to get up and running with Model is to create a new instance of the <code>Y.Model</code> 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).
91
Here's how you might create a simple model representing a delicious pie (imagine you're building an online ordering system for a bakery):
94
<pre class="code prettyprint">var applePie = new Y.Model({
95
slices: 6, // number of slices in this pie
96
type : 'apple' // what type of pie this is
101
This creates a new <code>Y.Model</code> instance named <code>applePie</code>, with two attributes: <code>slices</code> and <code>type</code>, in addition to the <a href="#built-in-attributes">built-in attributes</a> <code>id</code> and <code>clientId</code>, which are available on all models.
105
Pass the name of an attribute to the model's <code>get()</code> function to get that attribute's value.
108
<pre class="code prettyprint">applePie.get('slices'); // => 6
109
applePie.get('type'); // => "apple"</pre>
113
To change the value of an attribute, pass its name and new value to <code>set()</code>.
116
<pre class="code prettyprint">applePie.set('slices', 5); // someone ate a slice!</pre>
120
Read on to learn how to create custom model subclasses for representing more complex data and logic, or skip ahead to <a href="#model-events">Model Events</a> or <a href="#getting-and-setting-attribute-values">Getting and Setting Attribute Values</a> to learn more about how to take advantage of the useful state management functionality Model provides.
123
<h3 id="extending-ymodel">Extending <code>Y.Model</code></h3>
126
The ability to create ad-hoc models by instantiating <code>Y.Model</code> is convenient, but sometimes it can be useful to create a custom Model subclass by <em>extending</em> <code>Y.Model</code>. 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.
130
In this example, we'll create a <code>Y.PieModel</code> class. Each instance of this class will represent a delicious pie, fresh from the oven.
133
<pre class="code prettyprint">// Create a new Y.PieModel class that extends Y.Model.
134
Y.PieModel = Y.Base.create('pieModel', Y.Model, [], {
135
// Add prototype methods for your Model here if desired. These methods will be
136
// available to all instances of your Model.
138
// Returns true if all the slices of the pie have been eaten.
139
allGone: function () {
140
return this.get('slices') === 0;
143
// Consumes a slice of pie, or fires an `error` event if there are no slices
145
eatSlice: function () {
146
if (this.allGone()) {
147
this.fire('error', {
148
type : 'eat',
149
error: "Oh snap! There isn't any pie left."
152
this.set('slices', this.get('slices') - 1);
153
Y.log('You just ate a slice of delicious ' + this.get('type') + ' pie!');
158
// Add custom model attributes here. These attributes will contain your
159
// model's data. See the docs for Y.Attribute to learn more about defining
160
// attributes.
163
value: 6 // default value
167
value: 'apple'
174
Now we can create instances of <code>Y.PieModel</code> to represent delicious pies.
178
Each instance will have a <code>type</code> attribute containing the type of the pie and a <code>slices</code> attribute containing the number of slices remaining. We can call the <code>allGone()</code> method to check whether there are any slices left, and the <code>eatSlice()</code> method to eat a slice.
181
<pre class="code prettyprint">// Bake a delicious new pecan pie.
182
var pecanPie = new Y.PieModel({type: 'pecan'});
184
pecanPie.on('error', function (e) {
188
pecanPie.eatSlice(); // => "You just ate a slice of delicious pecan pie!"
189
Y.log(pecanPie.get('slices')); // => 5</pre>
193
Five slices later, our pie will be all gone. If we try to eat another slice, we'll get an <code>error</code> event.
196
<pre class="code prettyprint">// 5 slices later...
197
pecanPie.eatSlice(); // => "Oh snap! There isn't any pie left."</pre>
200
<h3 id="model-attributes">Model Attributes</h3>
203
A Model's data is represented by <a href="../attribute/index.html">attributes</a>. The Model class provides two built-in attributes, <code>clientId</code> and <code>id</code>. The rest are up to you to define when you extend <code>Y.Model</code>.
206
<h4 id="built-in-attributes">Built-in Attributes</h4>
212
<th>Default Value</th>
218
<td><code>clientId</code></td>
219
<td><em>generated id</em></td>
222
An automatically generated client-side only unique ID for identifying model instances that don't yet have an <code>id</code>. The client id is guaranteed to be unique among all models on the current page, but is not unique across pageviews. Client ids are never included in <code>toJSON()</code> output.
228
<td><code>id</code></td>
229
<td><code>null</code></td>
232
A globally unique identifier for the model instance. If this is <code>null</code>, then the model instance is assumed to be "new" (meaning it hasn't yet been saved to a persistence layer). If the model represents data that's stored in a database of some kind, it usually makes sense to use the database's primary key here.
236
If your persistence layer uses a primary key with a name other than <code>id</code>, you can override the <code>idAttribute</code> property and set it to the name of your custom id attribute when extending <code>Y.Model</code> (be sure to define a corresponding attribute as well). The <code>id</code> attribute will then act as an alias for your custom id attribute.
243
<h4 id="custom-attributes">Custom Attributes</h4>
246
Custom attributes are where all your model's data should live. You define these attributes when you first extend <code>Y.Model</code>. You can set their values by passing a config object into the model's constructor, or by calling the model's <code>set()</code> or <code>setAttrs()</code> methods..
250
Attributes can specify default values, getters and setters, validators, and more. For details, see the documentation for the <a href="../attribute/index.html">Attribute</a> component.
253
<h3 id="model-properties">Model Properties</h3>
256
The following properties are available on Model instances. The <code>idAttribute</code> property may be overridden when extending <code>Y.Model</code>; the others are intended to be read-only.
269
<td><code>changed</code></td>
273
Hash of attributes that have changed since the last time the model was saved.
279
<td><code>idAttribute</code></td>
283
Name of the attribute to use as the unique id for the model. Defaults to "id", but you may override this property when extending <code>Y.Model</code> if you want to specify a custom id attribute.
289
<td><code>lastChange</code></td>
293
Hash of attributes that were changed in the most recent <code>change</code> event. Each item in this hash is an object with the following properties:
296
<dl style="margin-top: 1em;">
297
<dt><strong><code>newVal</code></strong></dt>
300
The new value of the attribute after it changed.
304
<dt><strong><code>prevVal</code></strong></dt>
307
The old value of the attribute before it changed.
311
<dt><strong><code>src</code></strong></dt>
314
The source of the change, or <code>null</code> if no source was specified when the change was made.
318
This can be set to any string you want by passing an options object like <code>{src: 'foo'}</code> to the <code>set()</code> or <code>setAttrs()</code> methods when changing attribute values. Its purpose is to allow you to identify the source of the change later by inspecting the <code>src</code> property associated with an event, so choose a string that has meaning for your particular use case.
326
<td><code>lists</code></td>
330
Array of <a href="../model-list/index.html">ModelList</a> instances that contain this model.
334
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 <code>add()</code> and <code>remove()</code> methods.
341
<h3 id="model-events">Model Events</h3>
344
Model instances provide the following events:
357
<td><code>change</code></td>
360
One or more attributes on the model are changed.
365
<dt><code>changed</code> (<em>Object</em>)</dt>
368
Hash of change information for each attribute that changed. Keys are attribute names, values are objects with the following properties:
371
<dl style="margin-top: 1em;">
372
<dt><code>newVal</code></dt>
375
The new value of the attribute after it changed.
379
<dt><code>prevVal</code></dt>
382
The old value of the attribute before it changed.
386
<dt><code>src</code></dt>
389
The source of the change, or <code>null</code> if no source was specified when the change was made.
393
This can be set to any string you want by passing an options object like <code>{src: 'foo'}</code> to the <code>set()</code> or <code>setAttrs()</code> methods when changing attribute values. Its purpose is to allow you to identify the source of the change later by inspecting the <code>src</code> property associated with an event, so choose a string that has meaning for your particular use case.
403
<td><code>error</code></td>
406
An error occurs, such as when the model fails validation or a sync layer response can't be parsed.
411
<dt><code>error</code></dt>
414
Error message, object, or exception generated by the error. Calling <code>toString()</code> on this should result in a meaningful error message.
418
<dt><code>src</code></dt>
421
Source of the error. May be one of the following default sources, or any custom error source used by your Model subclass):
424
<dl style="margin-top: 1em;">
425
<dt><code>load</code></dt>
428
An error loading the model from a sync layer. The sync layer's response (if any) will be provided as the <code>response</code> property on the event facade.
432
<dt><code>parse</code></dt>
435
An error parsing a response from a sync layer.
439
<dt><code>save</code></dt>
442
An error saving the model to a sync layer. The sync layer's response (if any) will be provided as the <code>response</code> property on the event facade.
446
<dt><code>validate</code></dt>
449
The model failed to validate.
459
<td><code>load</code></td>
462
After model attributes are loaded from a sync layer.
467
<dt><code>parsed</code></dt>
470
The parsed version of the sync layer's response to the load request.
474
<dt><code>response</code></dt>
477
The sync layer's raw, unparsed response to the load request.
485
<td><code>save</code></td>
488
After model attributes are saved to a sync layer.
493
<dt><code>parsed</code></dt>
496
The parsed version of the sync layer's response to the save request.
500
<dt><code>response</code></dt>
503
The sync layer's raw, unparsed response to the save request.
513
A model's events bubble up to any <a href="../model-list/index.html">model lists</a> that the model belongs to. This enables you to use the model list as a central point for handling model value changes and errors.
516
<h4 id="change-events">Change Events</h4>
519
In addition to the master <code>change</code> event, which is fired whenever one or more attributes are changed, there are also change events for each individual attribute.
523
Attribute-level change events follow the naming scheme <code><em>name</em>Change</code>, where <em>name</em> is the name of an attribute.
526
<pre class="code prettyprint">// Bake a new pie model.
527
var pie = new Y.PieModel();
529
// Listen for all attribute changes.
530
pie.on('change', function (e) {
531
Y.log('change fired: ' + Y.Object.keys(e.changed).join(', '));
534
// Listen for changes to the `slices` attribute.
535
pie.on('slicesChange', function (e) {
536
Y.log('slicesChange fired');
539
// Listen for changes to the `type` attribute.
540
pie.on('typeChange', function (e) {
541
Y.log('typeChange fired');
544
// Change multiple attributes at once.
547
type : 'maple custard'
550
// => "slicesChange fired"
551
// => "typeChange fired"
552
// => "change fired: slices, type"</pre>
555
<h4 id="firing-your-own-error-events">Firing Your Own Error Events</h4>
558
In your custom model class, there may be situations beyond just parsing and validating in which an <code>error</code> event would be useful. For example, in the <code>Y.PieModel</code> class, we fire an error when someone tries to eat a slice of pie and there are no slices left.
561
<pre class="code prettyprint">// Consumes a slice of pie, or fires an `error` event if there are no slices
563
eatSlice: function () {
564
if (this.allGone()) {
565
this.fire('error', {
566
type : 'eat',
567
error: "Oh snap! There isn't any pie left."
570
this.set('slices', this.get('slices') - 1);
571
Y.log('You just ate a slice of delicious ' + this.get('type') + ' pie!');
577
When firing an error event, set the <code>type</code> 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.
581
The <code>error</code> property should be set to an error message, an Error object, or anything else that provides information about the error and has a <code>toString()</code> method that returns an error message string.
584
<h3 id="working-with-model-data">Working with Model Data</h3>
586
<h4 id="getting-and-setting-attribute-values">Getting and Setting Attribute Values</h4>
589
Model's <code>get()</code> and <code>set()</code> methods are the main ways of interacting with model attributes. Unsurprisingly, they allow you to get and set the value of a single attribute.
592
<pre class="code prettyprint">var pie = new Y.PieModel();
594
// Set the value of the `type` attribute.
595
pie.set('type', 'banana cream');
597
// Get the value of the `type` attribute.
598
pie.get('type'); // => "banana cream"</pre>
602
Model also provides two convenience methods for getting and escaping an attribute value in a single step. The <code>getAsHTML()</code> method returns an HTML-escaped value, and the <code>getAsURL()</code> method returns a URL-encoded value.
605
<pre class="code prettyprint">pie.set('type', 'strawberries & cream');
607
pie.getAsHTML('type'); // => "strawberries &amp; cream"
608
pie.getAsURL('type'); // => "strawberries%20%26%20cream"</pre>
612
The <code>getAttrs()</code> and <code>setAttrs()</code> methods may be used to get and set multiple attributes at once. <code>getAttrs()</code> returns a hash of all attribute values, while <code>setAttrs()</code> accepts a hash of attribute values. When you set multiple attributes with <code>setAttrs()</code>, it fires only a single change event that contains all the affected attributes..
615
<pre class="code prettyprint">pie.setAttrs({
617
type : 'marionberry'
622
// clientId: "pieModel_1",
623
// destroyed: false,
624
// id: null,
625
// initialized: true,
626
// slices: 6,
627
// type: "marionberry"
632
The <code>destroyed</code> and <code>initialized</code> attributes you see in the sample output above are lifecycle attributes provided by <code>Y.Base</code>, and aren't actually model data.
636
To get a slightly more useful representation of model data, use the <code>toJSON()</code> method. The <code>toJSON()</code> method excludes the <code>clientId</code>, <code>destroyed</code>, and <code>initialized</code> attributes, making the resulting object more suitable for serialization and for storing in a persistence layer.
639
<pre class="code prettyprint">pie.toJSON();
641
// id: null,
642
// slices: 6,
643
// type: "marionberry"
648
If a custom <code>idAttribute</code> is in use, the <code>toJSON()</code> output will include that id attribute instead of <code>id</code>.
651
<pre class="code prettyprint">// toJSON() output with a custom id attribute.
654
// customId: null,
655
// slices: 6,
656
// type: "marionberry"
661
If you'd like to customize the serialized representation of your models, you may override the <code>toJSON()</code> method.
665
When using the <code>set()</code> and <code>setAttrs()</code> methods, you may pass an optional <code>options</code> argument. If <code>options.silent</code> is <code>true</code>, no <code>change</code> event will be fired.
668
<pre class="code prettyprint">// Set attributes without firing a `change` event.
669
pie.set('slices', 0, {silent: true});
673
type : 'chocolate cream'
674
}, {silent: true});</pre>
678
After making changes to a model's attributes, you may call the <code>undo()</code> method to undo the previous change.
681
<pre class="code prettyprint">var pie = new Y.PieModel({slices: 6});
683
pie.set('slices', 5);
685
pie.get('slices'); // => 6</pre>
689
Note that there's only a single level of undo, so it's not possible to revert past the most recent change.
692
<h4 id="validating-changes">Validating Changes</h4>
695
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.
699
There are two ways to validate model attributes. One way is to define an attribute validator function for an individual attribute when you extend <code>Y.Model</code>.
702
<pre class="code prettyprint">// Defining an individual attribute validator.
703
Y.PieModel = Y.Base.create('pieModel', Y.Model, [], {
704
// ... prototype methods and properties ...
709
validator: function (value) {
710
return typeof value === 'number' && value >= 0 && value <= 10;
720
An attribute validator will be called whenever that attribute changes, and can prevent the change from taking effect by returning <code>false</code>. Model <code>error</code> events are not fired when attribute validators fail. For more details on attribute validators, see the <a href="../attribute/index.html">Attribute User Guide</a>.
724
The second way to validate changes is to provide a custom <code>validate()</code> method when extending <code>Y.Model</code>. The <code>validate()</code> method will be called automatically when <code>save()</code> is called, and will receive a hash of all the attributes in the model. If the <code>validate()</code> method returns anything other than <code>null</code> or <code>undefined</code>, it will be considered a validation failure, an <code>error</code> event will be fired with the returned value as the error message, and the <code>save()</code> action will be aborted.
727
<pre class="code prettyprint">// Defining a model-wide `validator()` method.
728
Y.PieModel = Y.Base.create('pieModel', Y.Model, [], {
729
// ... prototype methods and properties ...
731
validate: function (attributes) {
734
switch (attributes.type) {
735
case 'rhubarb':
736
return 'Eww. No. Not allowed.';
738
case 'maple custard':
739
slices = Y.Lang.isValue(attributes.slices) ?
740
attributes.slices : this.get('slices');
742
if (slices < 10) {
743
return "Making fewer than 10 slices of maple custard pie would be " +
744
"silly, because I'm just going to eat 8 of them as soon as it's " +
745
"out of the oven.";
750
// ... attributes ...
754
<h4 id="loading-and-saving-model-data">Loading and Saving Model Data</h4>
757
Calling a model's <code>load()</code> and <code>save()</code> methods will result in a behind-the-scenes call to the model's <code>sync()</code> method specifying the appropriate action.
761
The default <code>sync()</code> 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 <a href="#implementing-a-model-sync-layer">Implementing a Model Sync Layer</a> for more details.
765
The <code>load()</code> and <code>save()</code> 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.
769
The callback function will receive two parameters: an error (this parameter will be <code>null</code> or <code>undefined</code> if the operation was successful) and a response (which is the result of calling the model's <code>parse()</code> method with whatever response the sync layer returned).
773
The <code>load()</code> method calls <code>sync()</code> with the <code>read</code> action, and automatically updates the model with the response data (by passing it to <code>parse()</code> and then updating attributes based on the hash that <code>parse()</code> returns) before calling the callback.
776
<pre class="code prettyprint">var pie = new Y.PieModel({id: 'pie123'});
778
// Load a pie model, passing a callback that will run when the model has
779
// been loaded.
780
pie.load(function (err, response) {
782
// Success! The model now contains the loaded data.
788
The <code>save()</code> method will do one of two things: if the model is new (meaning it doesn't yet have an <code>id</code> value), it will call <code>sync()</code> with the "create" action. If the model is not new, then it will call <code>sync()</code> with the "update" action.
792
If the sync layer returns a response, then <code>save()</code> will update the model's attributes with the response data before calling the callback function.
795
<pre class="code prettyprint">// Save a pie model, passing a callback that will run when the model has
796
// been saved.
797
pie.save(function (err, response) {
799
// Success! The model has been saved. If the sync layer returned a response,
800
// then the model has also been updated with any new data in the response.
806
In addition to calling the specified callback (if any), the <code>load()</code> and <code>save()</code> methods will fire a <code>load</code> event and a <code>save</code> event respectively on success, or an <code>error</code> event on failure. See <a href="#model-events">Model Events</a> for more details on these events.
810
Always use the <code>load()</code> or <code>save()</code> methods rather than calling <code>sync()</code> directly, since this ensures that the sync layer's response is passed through the <code>parse()</code> method and that the model's data is updated if necessary.
813
<h2 id="the-model-lifecycle">The Model Lifecycle</h2>
816
When a model is first created and doesn't yet have an <code>id</code> value, it's considered "new". The <code>isNew()</code> method will tell you whether or not a model is new.
820
Once a model has an <code>id</code> 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.
824
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 <code>isModified()</code> method will tell you whether or not a model is modified. A successful call to <code>load()</code> or <code>save()</code> will reset a model's "modified" flag.
828
Finally, a model's <code>destroy()</code> method can be used to destroy the model instance. Calling <code>destroy()</code> with no arguments will destroy only the local model instance, while calling <code>destroy({remove: true})</code> 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.
832
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 <code>read</code> 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).
835
<h2 id="implementing-a-model-sync-layer">Implementing a Model Sync Layer</h2>
838
A model's <code>save()</code>, <code>load()</code>, and <code>destroy()</code> methods all internally call the model's <code>sync()</code> method to carry out an action. The default <code>sync()</code> method doesn't actually do anything, but by overriding the <code>sync()</code> method, you can provide a custom sync layer.
842
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.
845
<h3 id="the-sync-method">The <code>sync()</code> Method</h3>
848
When the <code>sync()</code> method is called, it receives three arguments:
852
<dt><strong><code>action</code> (<em>String</em>)</strong></dt>
855
A string that indicates the intended sync action. May be one of the following values:
859
<dt><strong><code>create</code></strong></dt>
862
Create a new model record. The "create" action occurs when a model is saved and doesn't yet have an <code>id</code> value.
866
<dt><strong><code>read</code></strong></dt>
869
Read an existing model record. The record should be identified based on the <code>id</code> attribute of the model.
873
<dt><strong><code>update</code></strong></dt>
876
Update an existing model record. The "update" action occurs when a model is saved and already has an <code>id</code> value. The record to be updated should be identified based on the <code>id</code> attribute of the model.
880
<dt><strong><code>delete</code></strong></dt>
883
Delete an existing model record. The record to be deleted should be identified based on the <code>id</code> attribute of the model.
889
<dt><strong><code>options</code> (<em>Object</em>)</strong></dt>
892
A hash containing any options that were passed to the <code>save()</code>, <code>load()</code> or <code>destroy()</code> method. This may be used to pass custom options to a sync layer.
896
<dt><strong><code>callback</code> (<em>Function</em>)</strong></dt>
899
A callback function that should be called when the sync operation is complete. The callback expects to receive the following arguments:
903
<dt><strong><code>err</code></strong></dt>
906
Error message or object if an error occured, <code>null</code> or <code>undefined</code> if the operation was successful.
910
<dt><strong><code>response</code></strong></dt>
913
Response from the persistence layer, if any. This will be passed to the <code>parse()</code> method to be parsed.
921
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 <code>json-stringify</code> module):
924
<pre class="code prettyprint">Y.PieModel = Y.Base.create('pieModel', Y.Model, [], {
925
// ... prototype methods and properties ...
927
// Custom sync layer.
928
sync: function (action, options, callback) {
932
case 'create':
933
data = this.toJSON();
935
// Use the current timestamp as an id just to simplify the example. In a
936
// real sync layer, you'd want to generate an id that's more likely to
937
// be globally unique.
938
data.id = Y.Lang.now();
940
// Store the new record in localStorage, then call the callback.
941
localStorage.setItem(data.id, Y.JSON.stringify(data));
942
callback(null, data);
945
case 'read':
946
// Look for an item in localStorage with this model's id.
947
data = localStorage.getItem(this.get('id'));
950
callback(null, data);
952
callback('Model not found.');
957
case 'update':
958
data = this.toJSON();
960
// Update the record in localStorage, then call the callback.
961
localStorage.setItem(this.get('id'), Y.JSON.stringify(data));
962
callback(null, data);
965
case 'delete':
966
localStorage.removeItem(this.get('id'));
971
callback('Invalid action');
975
// ... attributes ...
979
<h3 id="the-parse-method">The <code>parse()</code> Method</h3>
982
Depending on the kind of response your sync layer returns, you may need to override the <code>parse()</code> method as well. The default <code>parse()</code> 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 <code>parse()</code> method to provide a custom parser implementation.
986
If an error occurs while parsing a response, fire an <code>error</code> event with <code>type</code> "parse".
990
This sample demonstrates a custom parser for responses in which the model data is contained in a <code>data</code> property of the response object.
993
<pre class="code prettyprint">// Custom response parser.
994
parse: function (response) {
996
return response.data;
999
this.fire('error', {
1000
type : 'parse',
1001
error: 'No data in the response.'
1009
<div class="yui3-u-1-4">
1010
<div class="sidebar">
1012
<div id="toc" class="sidebox">
1014
<h2 class="no-toc">Table of Contents</h2>
1020
<a href="#getting-started">Getting Started</a>
1023
<a href="#what-is-a-model">What is a Model?</a>
1026
<a href="#using-model">Using Model</a>
1029
<a href="#quick-start">Quick Start</a>
1032
<a href="#extending-ymodel">Extending <code>Y.Model</code></a>
1035
<a href="#model-attributes">Model Attributes</a>
1038
<a href="#built-in-attributes">Built-in Attributes</a>
1041
<a href="#custom-attributes">Custom Attributes</a>
1046
<a href="#model-properties">Model Properties</a>
1049
<a href="#model-events">Model Events</a>
1052
<a href="#change-events">Change Events</a>
1055
<a href="#firing-your-own-error-events">Firing Your Own Error Events</a>
1060
<a href="#working-with-model-data">Working with Model Data</a>
1063
<a href="#getting-and-setting-attribute-values">Getting and Setting Attribute Values</a>
1066
<a href="#validating-changes">Validating Changes</a>
1069
<a href="#loading-and-saving-model-data">Loading and Saving Model Data</a>
1076
<a href="#the-model-lifecycle">The Model Lifecycle</a>
1079
<a href="#implementing-a-model-sync-layer">Implementing a Model Sync Layer</a>
1082
<a href="#the-sync-method">The <code>sync()</code> Method</a>
1085
<a href="#the-parse-method">The <code>parse()</code> Method</a>
1097
<div class="sidebox">
1099
<h2 class="no-toc">Examples That Use This Component</h2>
1103
<ul class="examples">
1106
<li data-description="A basic todo list built with the Model, Model List, and View components.">
1107
<a href="../app/app-todo.html">Todo List</a>
1112
<li data-description="An application to browse through the contributors of a GitHub project.">
1113
<a href="../app/app-contributors.html">GitHub Contributors</a>
1126
<script src="../assets/vendor/prettify/prettify-min.js"></script>
1127
<script>prettyPrint();</script>