5
<title>Model List</title>
6
<link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
7
<link rel="stylesheet" href="../assets/css/main.css">
8
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
9
<script src="../../build/yui/yui-min.js"></script>
17
<a href="#toc" class="jump">Jump to Table of Contents</a>
21
<div id="main" class="yui3-u">
22
<div class="content"><div class="intro">
24
A Model List is an array-like ordered list of <a href="../model/index.html">Model</a> instances with methods for adding, removing, sorting, filtering, and performing other actions on models in the list.
28
A Model instance may exist in zero or more lists. All events fired by a model automatically bubble up to all the lists that contain that model, so lists serve as convenient aggregators for model events.
32
<code>Y.ModelList</code> also exposes a sync API similar to the one used by <code>Y.Model</code>, making it easy to implement syncing logic to load lists of models from a persistence layer or remote server.
36
<h2 id="getting-started">Getting Started</h2>
39
To include the source files for Model List and its dependencies, first load
40
the YUI seed file if you haven't already loaded it.
43
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script></pre>
47
Next, create a new YUI instance for your application and populate it with the
48
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
49
YUI will automatically load any dependencies required by the modules you
53
<pre class="code prettyprint">// Create a new YUI instance and populate it with the required modules.
54
YUI().use('model-list', function (Y) {
55
// Model List is available and ready for use. Add implementation
56
// code here.
61
For more information on creating YUI instances and on the
62
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
63
documentation for the <a href="../yui/index.html">YUI Global object</a>.
67
<h2 id="using-model-list">Using Model List</h2>
69
<h3 id="instantiating-a-model-list">Instantiating a Model List</h3>
72
Most of the classes in the App Framework are meant to be extended, but if your needs are simple and you don't plan to implement a custom sort comparator or sync layer for your lists, you can probably just instantiate <code>Y.ModelList</code> directly.
75
<pre class="code prettyprint">// Instantiate a new list that will contain instances of the Y.PieModel model
77
var list = new Y.ModelList({model: Y.PieModel});</pre>
81
The <code>model</code> config parameter configures the list to contain models that are instances of the <code>Y.PieModel</code> class (which you can read more about in the <a href="../model/index.html">Model User Guide</a>).
85
You're not strictly required to provide a <code>model</code> class, but doing so will allow you to pass plain hashes of attributes to the list's <code>add()</code> and <code>create()</code> methods and have them automatically turned into model instances. If you don't specify a <code>model</code> class, you'll need to pass existing model instances to these methods.
88
<h3 id="extending-ymodellist">Extending <code>Y.ModelList</code></h3>
91
Extending the <code>Y.ModelList</code> class allows you to create a custom class in which you may provide a custom sort comparator function, sync layer, or other logic specific to your lists. This is optional, but is a great way to add custom functionality to a model list in an efficient and maintainable way.
95
In this example, we'll create a <code>Y.PieList</code> class. Each instance of this class will contain <code>Y.PieModel</code> instances representing delicious pies.
98
<pre class="code prettyprint">Y.PieList = Y.Base.create('pieList', Y.ModelList, [], {
99
// Add prototype properties and methods for your List here if desired. These
100
// will be available to all instances of your List.
102
// Specifies that this list is meant to contain instances of Y.PieModel.
105
// Returns an array of PieModel instances that have been eaten.
107
return Y.Array.filter(this.toArray(), function (model) {
108
return model.get('slices') === 0;
112
// Returns the total number of pie slices remaining among all the pies in
113
// the list.
114
totalSlices: function () {
117
this.each(function (model) {
118
slices += model.get('slices');
127
You can now create instances of <code>Y.PieList</code>.
130
<pre class="code prettyprint">var pies = new Y.PieList();</pre>
133
<h3 id="adding-removing-and-retrieving-models">Adding, Removing, and Retrieving Models</h3>
135
<h4 id="adding-models">Adding Models</h4>
138
Use the <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_add"><code>add()</code></a>, <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_create"><code>create()</code></a>, and <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_reset"><code>reset()</code></a> methods to put models into a list.
142
The difference between <code>add()</code> and <code>create()</code> is that <code>add()</code> simply adds one or more models to the list, while <code>create()</code> first saves a model and only adds it to the list once the model's sync layer indicates that the save operation was successful.
145
<pre class="code prettyprint">// Add a single model to the list.
146
pies.add(new Y.PieModel({type: 'pecan'}));
148
// Add multiple models to the list.
150
new Y.PieModel({type: 'apple'}),
151
new Y.PieModel({type: 'maple custard'})
154
// Save a model, then add it to the list.
155
pies.create(new Y.PieModel({type: 'pumpkin'}));</pre>
159
If your list's <code>model</code> property is set to a model class, then you can just pass attribute hashes to the <code>add()</code> and <code>create()</code> methods, and the list will automatically create new model instances for you.
162
<pre class="code prettyprint">// Add a single model to the list.
163
pies.add({type: 'pecan'});
165
// Add multiple models to the list.
167
{type: 'apple'},
168
{type: 'maple custard'}
171
// Save a model, then add it to the list.
172
pies.create({type: 'pumpkin'});</pre>
176
The <code>create()</code> method accepts an optional callback function, which will be executed when the save operation finishes. Provide a callback if you'd like to be notified of the success or failure of the save operation.
179
<pre class="code prettyprint">pies.create({type: 'watermelon chiffon'}, function (err) {
181
// The save operation was successful!
187
The <code>reset()</code> method removes any models that are already in the list and then adds the models you specify. Instead of generating many <code>add</code> and <code>remove</code> events, the <code>reset()</code> method only generates a single <code>reset</code> event. Use <code>reset()</code> when you need to repopulate the entire list efficiently.
190
<pre class="code prettyprint">// Remove all existing models from the list and add new ones.
192
{type: 'lemon meringue'},
193
{type: 'banana cream'}
198
You can also call <code>reset()</code> with no arguments to quickly empty the list.
201
<pre class="code prettyprint">// Empty the list.
206
Models are automatically inserted into the list at the correct index based on the current sort comparator, so the list is always guaranteed to be sorted. By default, no sort comparator is defined, so models are sorted in insertion order. See <a href="#creating-a-custom-sort-comparator">Creating a Custom Sort Comparator</a> for details on customizing how a list is sorted.
209
<h4 id="retrieving-models">Retrieving Models</h4>
212
Models in the list can be retrieved by their <code>id</code> attribute, their <code>clientId</code> attribute, or by their numeric index within the list.
215
<pre class="code prettyprint">// Look up a model by its id.
216
pies.getById('1234');
218
// Look up a model by its clientId.
219
pies.getByClientId('pie_42');
221
// Look up a model by its numeric index within the list.
224
// Find the index of a model instance within the list.
225
pies.indexOf(pies.getById('1234'));</pre>
228
<h4 id="removing-models">Removing Models</h4>
231
Pass a model or array of models to the <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_remove"><code>remove()</code></a> method to remove them from the list.
234
<pre class="code prettyprint">// Remove a single model from the list.
235
pies.remove(pies.getById('1234'));
237
// Remove multiple models from the list.
239
pies.getById('1235'),
240
pies.getById('1236')
245
This will only remove the specified model instances from the list; it won't actually call the models' <a href="http://yuilibrary.com/yui/docs/api/classes/Model.html#method_destroy"><code>destroy()</code></a> methods or delete them via the models' sync layer. Calling a model's <code>destroy()</code> method will automatically remove it from any lists it's in, so that would be a better option if you want to both remove and destroy or delete a model.
248
<h3 id="list-attributes">List Attributes</h3>
251
Model Lists themselves don't provide any attributes, but calling the <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_get"><code>get()</code></a>, <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_getAsHTML"><code>getAsHTML()</code></a>, or <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_getAsURL"><code>getAsURL()</code></a> methods on the list will return an array containing the specified attribute values from every model in the list.
254
<pre class="code prettyprint">pies.add([
255
{type: 'pecan'},
256
{type: 'strawberries & cream'},
257
{type: 'blueberry'}
260
pies.get('type');
261
// => ["pecan", "strawberries & cream", "blueberry"]
263
pies.getAsHTML('type');
264
// => ["pecan", "strawberries &amp; cream", "blueberry"]
266
pies.getAsURL('type');
267
// => ["pecan", "strawberries%20%26%20cream", "blueberry"]</pre>
270
<h3 id="list-events">List Events</h3>
273
Model List instances provide the following events:
286
<td><code>add</code></td>
287
<td>A model is added to the list.</td>
290
<dt><code>model</code> (<em>Y.Model</em>)</dt>
292
The model instance being added.
295
<dt><code>index</code> (<em>Number</em>)</dt>
297
The index at which the model will be added.
304
<td><code>error</code></td>
305
<td>An error occurs, such as when an attempt is made to add a duplicate model to the list, or when a sync layer response can't be parsed.</td>
308
<dt><code>error</code> (<em>Any</em>)</dt>
310
Error message, object, or exception generated by the error. Calling <code>toString()</code> on this should result in a meaningful error message.
313
<dt><code>src</code> (<em>String</em>)</dt>
316
Source of the error. May be one of the following (or any custom error source defined by a ModelList subclass):
320
<dt><code>add</code></dt>
322
Error while adding a model (probably because it's already in the list and can't be added again). The model in question will be provided as the <code>model</code> property on the event facade.
325
<dt><code>parse</code></dt>
327
An error parsing a JSON response. The response in question will be provided as the <code>response</code> property on the event facade.
330
<dt><code>remove</code></dt>
332
Error while removing a model (probably because it isn't in the list and can't be removed). The model in question will be provided as the <code>model</code> property on the event facade.
340
<td><code>remove</code></td>
341
<td>A model is removed from the list.</td>
344
<dt><code>model</code> (<em>Y.Model</em>)</dt>
346
The model instance being removed.
349
<dt><code>index</code> (<em>Number</em>)</dt>
351
The index of the model being removed.
358
<td><code>reset</code></td>
359
<td>The list is completely reset or sorted.</td>
362
<dt><code>models</code> (<em>Array</em>)</dt>
364
Array of the list's new models after the reset.
367
<dt><code>src</code> (<em>String</em>)</dt>
369
Source of the event. May be either "reset" or "sort".
378
Each of these events is preventable, which means you can subscribe to the "on" phase of an event and call <code>e.preventDefault()</code> in your subscriber function to prevent the event from actually occurring. This works because "on" subscribers actually run before an event causes any default logic to run.
382
For example, you could prevent a model from being added to the list like this:
385
<pre class="code prettyprint">pies.on('add', function (e) {
386
if (e.model.get('type') === 'rhubarb') {
387
// Eww. No rhubarb for me please.
394
If you only want to be notified <em>after</em> an event occurs, and only when that event wasn't prevented, subscribe to the "after" phase.
397
<pre class="code prettyprint">pies.after('add', function (e) {
398
// Only runs after a model is successfully added to the list.
402
<h4 id="subscribing-to-bubbled-model-events">Subscribing to Bubbled Model Events</h4>
405
A model's events bubble up to any model lists it belongs to. This means, for example, that you can subscribe to the <code>*:change</code> event on the list to be notified whenever the <code>change</code> event of any model in the list is fired.
408
<pre class="code prettyprint">// Subscribe to change events from all models in the `pies` model list.
409
pies.on('*:change', function (e) {
410
// e.target is a reference to the model instance that caused the event.
411
var model = e.target,
412
slices = e.changed.slices;
414
if (slices && slices.newVal < slices.prevVal) {
415
Y.log('Somebody just ate a slice of ' + model.get('type') + ' pie!');
421
If a model exists in more than one list, its events will bubble up to all the lists it's in.
424
<h3 id="manipulating-the-list">Manipulating the List</h3>
427
Model Lists extend <code>Y.ArrayList</code>, which means they provide many convenient array-like methods for manipulating the list of models.
431
For example, you can use <code>each()</code> and <code>some()</code> to iterate over the list, <code>size()</code> to get the number of models in the list, and <code>map()</code> to pass each model in the list to a function and return an array of that function's return values.
435
For more details, see the <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html">Model List API docs</a>.
438
<h2 id="creating-a-custom-sort-comparator">Creating a Custom Sort Comparator</h2>
441
When a model is added to a list, it's automatically inserted at the correct index to maintain the sort order of the list. This sort order is determined by the return value of the list's optional <code>comparator()</code> function.
445
By default, lists don't have a comparator function, so models are sorted in the order they're added. To customize how models are sorted, override your list's <code>comparator()</code> function with a function that accepts a single model instance as an argument and returns a value that should be compared with return values from other models to determine the sort order.
448
<pre class="code prettyprint">Y.PieList = Y.Base.create('pieList', Y.ModelList, [], {
449
// ... prototype methods and properties ...
451
// Custom comparator to keep pies sorted by type.
452
comparator: function (model) {
453
return model.get('type');
459
If you change the comparator function after models have already been added to the list, you can call the list's <code>sort()</code> function to re-sort the entire list.
462
<pre class="code prettyprint">// Change the comparator of a pie list and re-sort it after adding some pies.
463
var pies = new Y.PieList();
466
{type: 'chocolate cream', slices: 8},
467
{type: 'dutch apple', slices: 6}
470
pies.get('type');
471
// => ['chocolate cream', 'dutch apple']
473
pies.comparator = function (model) {
474
return model.get('slices');
479
pies.get('type');
480
// => ['dutch apple', 'chocolate cream']</pre>
484
Behind the scenes, ModelList passes each model to the <code>comparator()</code> method and then performs a simple natural order comparison on the return values to determine whether a given model should be sorted above, below, or at the same position as another model. The logic looks like this:
487
<pre class="code prettyprint">// `a` and `b` are both Model instances.
489
// `this` is the current ModelList instance.
490
var aValue = this.comparator(a),
491
bValue = this.comparator(b);
493
return aValue < bValue ? -1 : (aValue > bValue ? 1 : 0);
498
If necessary, you can override ModelList's protected <code>_sync()</code> method (note the underscore prefix) to further customize this sorting logic.
501
<h2 id="implementing-a-list-sync-layer">Implementing a List Sync Layer</h2>
504
A list's <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_load"><code>load()</code></a> method internally calls the list's <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_sync"><code>sync()</code></a> method to carry out the load 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.
508
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.
512
A Model List sync layer works exactly the same way as a <a href="../model/index.html">Model</a> sync layer, except that only the <code>read</code> action is currently supported.
515
<h3 id="the-sync-method">The <code>sync()</code> Method</h3>
518
When the <code>sync()</code> method is called, it receives three arguments:
522
<dt><strong><code>action</code> (<em>String</em>)</strong></dt>
525
A string that indicates the intended sync action. May be one of the following values:
529
<dt><strong><code>read</code></strong></dt>
532
Read an existing list of models.
536
<dd><em>Other values are not currently supported, but may be added in a future release.</em></dd>
540
<dt><strong><code>options</code> (<em>Object</em>)</strong></dt>
543
A hash containing any options that were passed to the <code>load()</code> method. This may be used to pass custom options to a sync layer.
547
<dt><strong><code>callback</code> (<em>Function</em>)</strong></dt>
550
A callback function that should be called when the sync operation is complete. The callback expects to receive the following arguments:
554
<dt><strong><code>err</code></strong></dt>
557
Error message or object if an error occured, <code>null</code> or <code>undefined</code> if the operation was successful.
561
<dt><strong><code>response</code></strong></dt>
564
Response from the persistence layer, if any. This will be passed to the <code>parse()</code> method to be parsed.
572
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 loads a list of models from local storage:
575
<pre class="code prettyprint">Y.PieList = Y.Base.create('pieList', Y.ModelList, [], {
576
// ... prototype methods and properties ...
578
// Custom sync layer.
579
sync: function (action, options, callback) {
582
if (action === 'read') {
583
data = localStorage.getItem('pies') || [];
584
callback(null, data);
586
callback('Unsupported sync action: ' + action);
592
<h3 id="the-parse-method">The <code>parse()</code> Method</h3>
595
Depending on the kind of response your sync layer returns, you may need to override the <a href="http://yuilibrary.com/yui/docs/api/classes/ModelList.html#method_parse"><code>parse()</code></a> method as well. The default <code>parse()</code> implementation can parse either a JavaScript array of model hashes or a JSON string that represents a JavaScript array of model hashes. If your response data is in another format, such as a nested JSON object or XML, override the <code>parse()</code> method to provide a custom parser implementation.
599
If an error occurs while parsing a response, fire an <code>error</code> event with <code>type</code> "parse".
603
This sample demonstrates a custom parser for responses in which the list data is contained in a <code>data</code> property of the response object.
606
<pre class="code prettyprint">// Custom response parser.
607
parse: function (response) {
609
return response.data;
612
this.fire('error', {
613
type : 'parse',
614
error: 'No data in the response.'
621
<div id="sidebar" class="yui3-u">
623
<div id="toc" class="sidebox">
625
<h2 class="no-toc">Table of Contents</h2>
631
<a href="#getting-started">Getting Started</a>
634
<a href="#using-model-list">Using Model List</a>
637
<a href="#instantiating-a-model-list">Instantiating a Model List</a>
640
<a href="#extending-ymodellist">Extending <code>Y.ModelList</code></a>
643
<a href="#adding-removing-and-retrieving-models">Adding, Removing, and Retrieving Models</a>
646
<a href="#adding-models">Adding Models</a>
649
<a href="#retrieving-models">Retrieving Models</a>
652
<a href="#removing-models">Removing Models</a>
657
<a href="#list-attributes">List Attributes</a>
660
<a href="#list-events">List Events</a>
663
<a href="#subscribing-to-bubbled-model-events">Subscribing to Bubbled Model Events</a>
668
<a href="#manipulating-the-list">Manipulating the List</a>
673
<a href="#creating-a-custom-sort-comparator">Creating a Custom Sort Comparator</a>
676
<a href="#implementing-a-list-sync-layer">Implementing a List Sync Layer</a>
679
<a href="#the-sync-method">The <code>sync()</code> Method</a>
682
<a href="#the-parse-method">The <code>parse()</code> Method</a>
694
<div class="sidebox">
696
<h2 class="no-toc">Examples That Use This Component</h2>
700
<ul class="examples">
703
<li data-description="A basic todo list built with the Model, Model List, and View components.">
704
<a href="../app/app-todo.html">Todo List</a>
716
<script src="../assets/vendor/prettify/prettify-min.js"></script>
717
<script>prettyPrint();</script>