A Model List is an array-like ordered list of Model instances with methods for adding, removing, sorting, filtering, and performing other actions on models in the list.
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.
Y.ModelList
also exposes a sync API similar to the one used by Y.Model
, making it easy to implement syncing logic to load lists of models from a persistence layer or remote server.
Getting Started
To include the source files for Model List and its dependencies, first load the YUI seed file if you haven't already loaded it.
<script src="http://yui.yahooapis.com/3.4.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.
// Create a new YUI instance and populate it with the required modules. YUI().use('model-list', function (Y) { // Model List is available and ready for use. Add implementation // code here. });
For more information on creating YUI instances and on the
use()
method, see the
documentation for the YUI Global object.
Using Model List
Instantiating a Model List
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 Y.ModelList
directly.
// Instantiate a new list that will contain instances of the Y.PieModel model // class. var list = new Y.ModelList({model: Y.PieModel});
The model
config parameter configures the list to contain models that are instances of the Y.PieModel
class (which you can read more about in the Model User Guide).
You're not strictly required to provide a model
class, but doing so will allow you to pass plain hashes of attributes to the list's add()
and create()
methods and have them automatically turned into model instances. If you don't specify a model
class, you'll need to pass existing model instances to these methods.
Extending Y.ModelList
Extending the Y.ModelList
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.
In this example, we'll create a Y.PieList
class. Each instance of this class will contain Y.PieModel
instances representing delicious pies.
Y.PieList = Y.Base.create('pieList', Y.ModelList, [], { // Add prototype properties and methods for your List here if desired. These // will be available to all instances of your List. // Specifies that this list is meant to contain instances of Y.PieModel. model: Y.PieModel, // Returns an array of PieModel instances that have been eaten. eaten: function () { return Y.Array.filter(this.toArray(), function (model) { return model.get('slices') === 0; }); }, // Returns the total number of pie slices remaining among all the pies in // the list. totalSlices: function () { var slices = 0; this.each(function (model) { slices += model.get('slices'); }); return slices; } });
You can now create instances of Y.PieList
.
var pies = new Y.PieList();
Adding, Removing, and Retrieving Models
Adding Models
Use the add()
, create()
, and reset()
methods to put models into a list.
The difference between add()
and create()
is that add()
simply adds one or more models to the list, while create()
first saves a model and only adds it to the list once the model's sync layer indicates that the save operation was successful.
// Add a single model to the list. pies.add(new Y.PieModel({type: 'pecan'})); // Add multiple models to the list. pies.add([ new Y.PieModel({type: 'apple'}), new Y.PieModel({type: 'maple custard'}) ]); // Save a model, then add it to the list. pies.create(new Y.PieModel({type: 'pumpkin'}));
If your list's model
property is set to a model class, then you can just pass attribute hashes to the add()
and create()
methods, and the list will automatically create new model instances for you.
// Add a single model to the list. pies.add({type: 'pecan'}); // Add multiple models to the list. pies.add([ {type: 'apple'}, {type: 'maple custard'} ]); // Save a model, then add it to the list. pies.create({type: 'pumpkin'});
The create()
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.
pies.create({type: 'watermelon chiffon'}, function (err) { if (!err) { // The save operation was successful! } });
The reset()
method removes any models that are already in the list and then adds the models you specify. Instead of generating many add
and remove
events, the reset()
method only generates a single reset
event. Use reset()
when you need to repopulate the entire list efficiently.
// Remove all existing models from the list and add new ones. pies.reset([ {type: 'lemon meringue'}, {type: 'banana cream'} ]);
You can also call reset()
with no arguments to quickly empty the list.
// Empty the list. pies.reset();
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 Creating a Custom Sort Comparator for details on customizing how a list is sorted.
Retrieving Models
Models in the list can be retrieved by their id
attribute, their clientId
attribute, or by their numeric index within the list.
// Look up a model by its id. pies.getById('1234'); // Look up a model by its clientId. pies.getByClientId('pie_42'); // Look up a model by its numeric index within the list. pies.item(0); // Find the index of a model instance within the list. pies.indexOf(pies.getById('1234'));
Removing Models
Pass a model or array of models to the remove()
method to remove them from the list.
// Remove a single model from the list. pies.remove(pies.getById('1234')); // Remove multiple models from the list. pies.remove([ pies.getById('1235'), pies.getById('1236') ]);
This will only remove the specified model instances from the list; it won't actually call the models' destroy()
methods or delete them via the models' sync layer. Calling a model's destroy()
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.
List Attributes
Model Lists themselves don't provide any attributes, but calling the get()
, getAsHTML()
, or getAsURL()
methods on the list will return an array containing the specified attribute values from every model in the list.
pies.add([ {type: 'pecan'}, {type: 'strawberries & cream'}, {type: 'blueberry'} ]); pies.get('type'); // => ["pecan", "strawberries & cream", "blueberry"] pies.getAsHTML('type'); // => ["pecan", "strawberries & cream", "blueberry"] pies.getAsURL('type'); // => ["pecan", "strawberries%20%26%20cream", "blueberry"]
List Events
Model List instances provide the following events:
Event | When | Payload |
---|---|---|
add |
A model is added to the list. |
|
error |
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. |
|
remove |
A model is removed from the list. |
|
reset |
The list is completely reset or sorted. |
|
Each of these events is preventable, which means you can subscribe to the "on" phase of an event and call e.preventDefault()
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.
For example, you could prevent a model from being added to the list like this:
pies.on('add', function (e) { if (e.model.get('type') === 'rhubarb') { // Eww. No rhubarb for me please. e.preventDefault(); } });
If you only want to be notified after an event occurs, and only when that event wasn't prevented, subscribe to the "after" phase.
pies.after('add', function (e) { // Only runs after a model is successfully added to the list. });
Subscribing to Bubbled Model Events
A model's events bubble up to any model lists it belongs to. This means, for example, that you can subscribe to the *:change
event on the list to be notified whenever the change
event of any model in the list is fired.
// Subscribe to change events from all models in the `pies` model list. pies.on('*:change', function (e) { // e.target is a reference to the model instance that caused the event. var model = e.target, slices = e.changed.slices; if (slices && slices.newVal < slices.prevVal) { Y.log('Somebody just ate a slice of ' + model.get('type') + ' pie!'); } });
If a model exists in more than one list, its events will bubble up to all the lists it's in.
Manipulating the List
Model Lists extend Y.ArrayList
, which means they provide many convenient array-like methods for manipulating the list of models.
For example, you can use each()
and some()
to iterate over the list, size()
to get the number of models in the list, and map()
to pass each model in the list to a function and return an array of that function's return values.
For more details, see the Model List API docs.
Creating a Custom Sort Comparator
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 comparator()
function.
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 comparator()
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.
Y.PieList = Y.Base.create('pieList', Y.ModelList, [], { // ... prototype methods and properties ... // Custom comparator to keep pies sorted by type. comparator: function (model) { return model.get('type'); } });
If you change the comparator function after models have already been added to the list, you can call the list's sort()
function to re-sort the entire list.
// Change the comparator of a pie list and re-sort it after adding some pies. var pies = new Y.PieList(); pies.add([ {type: 'chocolate cream', slices: 8}, {type: 'dutch apple', slices: 6} ]); pies.get('type'); // => ['chocolate cream', 'dutch apple'] pies.comparator = function (model) { return model.get('slices'); }; pies.sort(); pies.get('type'); // => ['dutch apple', 'chocolate cream']
Behind the scenes, ModelList passes each model to the comparator()
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:
// `a` and `b` are both Model instances. function (a, b) { // `this` is the current ModelList instance. var aValue = this.comparator(a), bValue = this.comparator(b); return aValue < bValue ? -1 : (aValue > bValue ? 1 : 0); }
If necessary, you can override ModelList's protected _sync()
method (note the underscore prefix) to further customize this sorting logic.
Implementing a List Sync Layer
A list's load()
method internally calls the list's sync()
method to carry out the load action. The default sync()
method doesn't actually do anything, but by overriding the sync()
method, you can provide a custom 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.
A Model List sync layer works exactly the same way as a Model sync layer, except that only the read
action is currently supported.
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:
read
-
Read an existing list of models.
- Other values are not currently supported, but may be added in a future release.
options
(Object)-
A hash containing any options that were passed to the
load()
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 loads a list of models from local storage:
Y.PieList = Y.Base.create('pieList', Y.ModelList, [], { // ... prototype methods and properties ... // Custom sync layer. sync: function (action, options, callback) { var data; if (action === 'read') { data = localStorage.getItem('pies') || []; callback(null, data); } else { callback('Unsupported sync action: ' + action); } } });
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 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 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 list 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.' }); }