model-list-debug.js revision 213abf076aeae2f3b6b834155b0a5b7dbae72d7c
/**
Provides an API for managing an ordered list of Model instances.
@submodule model-list
@since 3.4.0
**/
/**
Provides an API for managing an ordered list of Model instances.
In addition to providing convenient `add`, `create`, `reset`, and `remove`
methods for managing the models in the list, ModelLists are also bubble targets
for events on the model instances they contain. This means, for example, that
you can add several models to a list, and then subscribe to the `*:change` event
on the list to be notified whenever any model in the list changes.
ModelLists also maintain sort order efficiently as models are added and removed,
based on a custom `comparator` function you may define (if no comparator is
defined, models are sorted in insertion order).
@class ModelList
@extends Base
@uses ArrayList
@constructor
@since 3.4.0
**/
YArray = Y.Array,
/**
Fired when a model is added to the list.
Listen to the `on` phase of this event to be notified before a model is
added to the list. Calling `e.preventDefault()` during the `on` phase will
prevent the model from being added.
Listen to the `after` phase of this event to be notified after a model has
been added to the list.
@event add
@param {Model} model The model being added.
@param {Number} index The index at which the model will be added.
@preventable _defAddFn
**/
EVT_ADD = 'add',
/**
Fired when 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.
@event error
@param {Any} error Error message, object, or exception generated by the
error. Calling `toString()` on this should result in a meaningful error
message.
@param {String} src Source of the error. May be one of the following (or any
custom error source defined by a ModelList subclass):
* `add`: 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 `model` property on the event facade.
* `parse`: An error parsing a JSON response. The response in question will
be provided as the `response` property on the event facade.
* `remove`: 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 `model` property on the event facade.
**/
EVT_ERROR = 'error';
/**
Fired when the list is completely reset via the `reset()` method or sorted
via the `sort()` method.
Listen to the `on` phase of this event to be notified before the list is
reset. Calling `e.preventDefault()` during the `on` phase will prevent
the list from being reset.
Listen to the `after` phase of this event to be notified after the list has
been reset.
@event reset
@param {Model[]} models Array of the list's new models after the reset.
@param {String} src Source of the event. May be either `'reset'` or
`'sort'`.
@preventable _defResetFn
**/
EVT_RESET = 'reset',
/**
Fired when a model is removed from the list.
Listen to the `on` phase of this event to be notified before a model is
removed from the list. Calling `e.preventDefault()` during the `on` phase
will prevent the model from being removed.
Listen to the `after` phase of this event to be notified after a model has
been removed from the list.
@event remove
@param {Model} model The model being removed.
@param {int} index The index of the model being removed.
@preventable _defRemoveFn
**/
EVT_REMOVE = 'remove';
function ModelList() {
}
// -- Public Properties ----------------------------------------------------
/**
The `Model` class or subclass of the models in this list.
This property is `null` by default, and is intended to be overridden in a
subclass or specified as a config property at instantiation time. It will be
used to create model instances automatically based on attribute hashes
passed to the `add()`, `create()`, and `reset()` methods.
@property model
@type Model
@default `null`
**/
model: null,
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
if (model) {
} else {
}
this._clear();
},
destructor: function () {
},
// -- Public Methods -------------------------------------------------------
/**
Adds the specified model or array of models to this list.
@example
// Add a single model instance.
list.add(new Model({foo: 'bar'}));
// Add a single model, creating a new instance automatically.
list.add({foo: 'bar'});
// Add multiple models, creating new instances automatically.
list.add([
{foo: 'bar'},
{baz: 'quux'}
]);
@method add
@param {Model|Model[]|Object|Object[]} models Models to add. May be existing
model instances or hashes of model attributes, in which case new model
instances will be created from the hashes.
@param {Object} [options] Data to be mixed into the event facade of the
`add` event(s) for the added models.
@param {Boolean} [options.silent=false] If `true`, no `add` event(s) will
be fired.
@return {Model|Model[]} Added model or array of added models.
**/
}, this);
} else {
}
},
/**
Define this method to provide a function that takes a model as a parameter
and returns a value by which that model should be sorted relative to other
models in this list.
By default, no comparator is defined, meaning that models will not be sorted
(they'll be stored in the order they're added).
@example
var list = new Y.ModelList({model: Y.Model});
list.comparator = function (model) {
return model.get('id'); // Sort models by id.
};
@method comparator
@param {Model} model Model being sorted.
@return {Number|String} Value by which the model should be sorted relative
to other models in this list.
**/
// comparator is not defined by default
/**
Creates or updates the specified model on the server, then adds it to this
list if the server indicates success.
@method create
@param {Model|Object} model Model to create. May be an existing model
instance or a hash of model attributes, in which case a new model instance
will be created from the hash.
@param {Object} [options] Options to be passed to the model's `sync()` and
`set()` methods and mixed into the `add` event when the model is added
to the list.
@param {Boolean} [options.silent=false] If `true`, no `add` event(s) will
be fired.
@param {callback} [callback] Called when the sync operation finishes.
@param {Error} callback.err If an error occurred, this parameter will
contain the error. If the sync operation succeeded, _err_ will be
falsy.
@param {mixed} callback.response The server's response.
@return {Model} Created model.
**/
var self = this;
// Allow callback as second arg.
if (typeof options === 'function') {
options = {};
}
}
if (!err) {
}
});
},
/**
If _name_ refers to an attribute on this ModelList instance, returns the
value of that attribute. Otherwise, returns an array containing the values
of the specified attribute from each model in this list.
@method get
@param {String} name Attribute name or object property path.
@return {Any|Array} Attribute value or array of attribute values.
@see Model.get()
**/
}
},
/**
If _name_ refers to an attribute on this ModelList instance, returns the
HTML-escaped value of that attribute. Otherwise, returns an array containing
the HTML-escaped values of the specified attribute from each model in this
list.
The values are escaped using `Escape.html()`.
@method getAsHTML
@param {String} name Attribute name or object property path.
@return {String|String[]} HTML-escaped value or array of HTML-escaped
values.
@see Model.getAsHTML()
**/
}
},
/**
If _name_ refers to an attribute on this ModelList instance, returns the
URL-encoded value of that attribute. Otherwise, returns an array containing
the URL-encoded values of the specified attribute from each model in this
list.
The values are encoded using the native `encodeURIComponent()` function.
@method getAsURL
@param {String} name Attribute name or object property path.
@return {String|String[]} URL-encoded value or array of URL-encoded values.
@see Model.getAsURL()
**/
}
},
/**
Returns the model with the specified _clientId_, or `null` if not found.
@method getByClientId
@param {String} clientId Client id.
@return {Model} Model, or `null` if not found.
**/
getByClientId: function (clientId) {
return this._clientIdMap[clientId] || null;
},
/**
Returns the model with the specified _id_, or `null` if not found.
Note that models aren't expected to have an id until they're saved, so if
you're working with unsaved models, it may be safer to call
`getByClientId()`.
@method getById
@param {String} id Model id.
@return {Model} Model, or `null` if not found.
**/
},
/**
Calls the named method on every model in the list. Any arguments provided
after _name_ will be passed on to the invoked method.
@method invoke
@param {String} name Name of the method to call on each model.
@param {Any} [args*] Zero or more arguments to pass to the invoked method.
@return {Array} Array of return values, indexed according to the index of
the model on which the method was called.
**/
},
/**
Returns the model at the specified _index_.
@method item
@param {int} index Index of the model to fetch.
@return {Model} The model at the specified index, or `undefined` if there
isn't a model there.
**/
// item() is inherited from ArrayList.
/**
Loads this list of models from the server.
This method delegates to the `sync()` method to perform the actual load
operation, which is an asynchronous action. Specify a _callback_ function to
be notified of success or failure.
If the load operation succeeds, a `reset` event will be fired.
@method load
@param {Object} [options] Options to be passed to `sync()` and to
`reset()` when adding the loaded models. It's up to the custom sync
implementation to determine what options it supports or requires, if any.
@param {callback} [callback] Called when the sync operation finishes.
@param {Error} callback.err If an error occurred, this parameter will
contain the error. If the sync operation succeeded, _err_ will be
falsy.
@param {mixed} callback.response The server's response. This value will
be passed to the `parse()` method, which is expected to parse it and
return an array of model attribute hashes.
@chainable
**/
var self = this;
// Allow callback as only arg.
if (typeof options === 'function') {
options = {};
}
if (!err) {
}
});
return this;
},
/**
Executes the specified function on each model in this list and returns an
array of the function's collected return values.
@method map
@param {Function} fn Function to execute on each model.
@param {Model} fn.model Current model being iterated.
@param {int} fn.index Index of the current model in the list.
@param {Model[]} fn.models Array of models being iterated.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {Array} Array of return values from _fn_.
**/
},
/**
Called to parse the _response_ when the list is loaded from the server.
This method receives a server _response_ and is expected to return an array
of model attribute hashes.
The default implementation assumes that _response_ is either an array of
attribute hashes or a JSON string that can be parsed into an array of
attribute hashes. If _response_ is a JSON string and either `Y.JSON` or the
native `JSON` object are available, it will be parsed automatically. If a
parse error occurs, an `error` event will be fired and the model will not be
updated.
You may override this method to implement custom parsing logic if necessary.
@method parse
@param {mixed} response Server response.
@return {Object[]} Array of model attribute hashes.
**/
if (typeof response === 'string') {
try {
} catch (ex) {
src : 'parse'
});
return null;
}
}
return response || [];
},
/**
Removes the specified model or array of models from this list.
@method remove
@param {Model|Model[]} models Models to remove.
@param {Object} [options] Data to be mixed into the event facade of the
`remove` event(s) for the removed models.
@param {Boolean} [options.silent=false] If `true`, no `remove` event(s)
will be fired.
@return {Model|Model[]} Removed model or array of removed models.
**/
}, this);
} else {
}
},
/**
Completely replaces all models in the list with those specified, and fires a
single `reset` event.
Use `reset` when you want to add or remove a large number of items at once
without firing `add` or `remove` events for each one.
@method reset
@param {Model[]|Object[]} [models] Models to add. May be existing model
instances or hashes of model attributes, in which case new model instances
will be created from the hashes. Calling `reset()` without passing in any
models will clear the list.
@param {Object} [options] Data to be mixed into the event facade of the
`reset` event.
@param {Boolean} [options.silent=false] If `true`, no `reset` event will
be fired.
@chainable
**/
src : 'reset',
}, this)
});
// Sort the models in the facade before firing the reset event.
if (this.comparator) {
}
return this;
},
/**
Forcibly re-sorts the list.
Usually it shouldn't be necessary to call this method since the list
maintains its sort order when items are added and removed, but if you change
the `comparator` function after items are already in the list, you'll need
to re-sort.
@method sort
@param {Object} [options] Data to be mixed into the event facade of the
`reset` event.
@param {Boolean} [options.silent=false] If `true`, no `reset` event will
be fired.
@chainable
**/
if (!this.comparator) {
return this;
}
src : 'sort'
});
return this;
},
/**
Override this method to provide a custom persistence implementation for this
list. The default method just calls the callback without actually doing
anything.
This method is called internally by `load()`.
@method sync
@param {String} action Sync action to perform. May be one of the following:
* `create`: Store a list of newly-created models for the first time.
* `delete`: Delete a list of existing models.
* `read` : Load a list of existing models.
* `update`: Update a list of existing models.
Currently, model lists only make use of the `read` action, but other
actions may be used in future versions.
@param {Object} [options] Sync options. It's up to the custom sync
implementation to determine what options it supports or requires, if any.
@param {callback} [callback] Called when the sync operation finishes.
@param {Error} callback.err If an error occurred, this parameter will
contain the error. If the sync operation succeeded, _err_ will be
falsy.
@param {mixed} [callback.response] The server's response. This value will
be passed to the `parse()` method, which is expected to parse it and
return an array of model attribute hashes.
**/
sync: function (/* action, options, callback */) {
if (typeof callback === 'function') {
callback();
}
},
/**
Returns an array containing the models in this list.
@method toArray
@return {Array} Array containing the models in this list.
**/
toArray: function () {
},
/**
Returns an array containing attribute hashes for each model in this list,
suitable for being passed to `Y.JSON.stringify()`.
Under the hood, this method calls `toJSON()` on each model in the list and
pushes the results into an array.
@method toJSON
@return {Object[]} Array of model attribute hashes.
@see Model.toJSON()
**/
toJSON: function () {
});
},
// -- Protected Methods ----------------------------------------------------
/**
Adds the specified _model_ if it isn't already in this list.
@method _add
@param {Model|Object} model Model or object to add.
@param {Object} [options] Data to be mixed into the event facade of the
`add` event for the added model.
@param {Boolean} [options.silent=false] If `true`, no `add` event will be
fired.
@return {Model} The added model.
@protected
**/
var facade;
}
error: 'Model is already in the list.',
src : 'add'
});
return;
}
});
return model;
},
/**
Adds this list as a bubble target for the specified model's events.
@method _attachList
@param {Model} model Model to attach to this list.
@protected
**/
_attachList: function (model) {
// Attach this list and make it a bubble target for the model.
},
/**
Clears all internal state and the internal list of models, returning this
list to an empty state. Automatically detaches all models in the list.
@method _clear
@protected
**/
_clear: function () {
this._clientIdMap = {};
this._idMap = {};
this._items = [];
},
/**
Removes this list as a bubble target for the specified model's events.
@method _detachList
@param {Model} model Model to detach.
@protected
**/
_detachList: function (model) {
if (index > -1) {
model.removeTarget(this);
}
},
/**
Returns the index at which the given _model_ should be inserted to maintain
the sort order of the list.
@method _findIndex
@param {Model} model The model being inserted.
@return {int} Index at which the model should be inserted.
@protected
**/
_findIndex: function (model) {
var comparator = this.comparator,
min = 0,
// Perform an iterative binary search to determine the correct position
// based on the return value of the `comparator` function.
} else {
}
}
return min;
},
/**
Removes the specified _model_ if it's in this list.
@method _remove
@param {Model} model Model to remove.
@param {Object} [options] Data to be mixed into the event facade of the
`remove` event for the removed model.
@param {Boolean} [options.silent=false] If `true`, no `remove` event will
be fired.
@return {Model} Removed model.
@protected
**/
if (index === -1) {
error: 'Model is not in the list.',
src : 'remove'
});
return;
}
});
return model;
},
/**
Array sort function used by `sort()` to re-sort the models in the list.
@method _sort
@param {Model} a First model to compare.
@param {Model} b Second model to compare.
@return {Number} `-1` if _a_ is less than _b_, `0` if equal, `1` if greater.
@protected
**/
_sort: function (a, b) {
var aValue = this.comparator(a),
bValue = this.comparator(b);
},
// -- Event Handlers -------------------------------------------------------
/**
Updates the model maps when a model's `id` attribute changes.
@method _afterIdChange
@param {EventFacade} e
@protected
**/
_afterIdChange: function (e) {
},
// -- Default Event Handlers -----------------------------------------------
/**
Default event handler for `add` events.
@method _defAddFn
@param {EventFacade} e
@protected
**/
_defAddFn: function (e) {
if (id) {
}
this._attachList(model);
},
/**
Default event handler for `remove` events.
@method _defRemoveFn
@param {EventFacade} e
@protected
**/
_defRemoveFn: function (e) {
this._detachList(model);
if (id) {
}
},
/**
Default event handler for `reset` events.
@method _defResetFn
@param {EventFacade} e
@protected
**/
_defResetFn: function (e) {
// When fired from the `sort` method, we don't need to clear the list or
// add any models, since the existing models are sorted in place.
if (e.src === 'sort') {
return;
}
this._clear();
}
}
}, {
NAME: 'modelList'
});
}, '@VERSION@' ,{requires:['array-extras', 'array-invoke', 'arraylist', 'base-build', 'escape', 'json-parse', 'model']});