|
YUI.add('RelatedModelList', function (Y) { |
|
|
|
|
|
/** |
|
* Intended as augmentation of Model to enable easy loading |
|
* of related ModelList instances. For example, an author Model |
|
* may have a BookList ModelList. |
|
* |
|
* The ModelList that is instantiated will need to know what |
|
* to do to load, save etc the data: this is up to the implementer. |
|
* |
|
*/ |
|
|
|
var r = function () { |
|
|
|
}, |
|
Lang = Y.Lang; |
|
|
|
|
|
|
|
r.prototype = { |
|
|
|
/** |
|
* @property _relatedLists |
|
* @type {Object} |
|
* @description A hash of previously requested related lists |
|
* to use as a cache |
|
*/ |
|
_relatedLists: {}, |
|
|
|
// -- Public methods -------------------------------------------------- |
|
|
|
|
|
/** |
|
@method related |
|
@param {String} Name of the ModelList extension to use (available on Y) |
|
@param {Boolean} Whether to create a new list if it's been |
|
previously requested and cached. The old one |
|
will not be destroyed, but the internal cache |
|
will overwrite the old list. |
|
@return {ModelList|false} |
|
@description Loads a ModelList that is related to the current |
|
Model. This is not the same as a list containing the |
|
Model. |
|
@example |
|
|
|
var shakey = new Author({id: 123}); |
|
shakey.on("change", function () {Y.log(shakey.get("name");}); |
|
shakey.load(); |
|
// "William Shakespeare" |
|
|
|
var books = shakey.related("BookList"); |
|
// BookList needs an attribute Author_id: this will be set to the |
|
// Author's id (i.e. books.get("Author_id") === 123) |
|
books.on("add", function () {Y.log(books.item(0).get("title"));}); |
|
books.load(); |
|
// "Romeo and Juliet" |
|
|
|
**/ |
|
related: function (listClassName, refresh) { |
|
|
|
var relatedLists = this._relatedLists, |
|
list, |
|
modelidref = '', |
|
refresh = refresh || false; |
|
|
|
if (!Lang.isString(listClassName)) { |
|
Y.error("method related() expects a string as first argument"); |
|
return false; |
|
} |
|
|
|
// Used cached version if it exists (and not wanting to refresh) |
|
if (relatedLists[listClassName] !== undefined && !refresh) { |
|
return relatedLists[listClassName]; |
|
} |
|
|
|
// Check whether the model list class exists |
|
if (!Y.Object.owns(Y, listClassName)) { |
|
Y.error("Model class " + listClassName + " is not available on Y"); |
|
return false; |
|
} |
|
|
|
// Set up the new model list and return it: |
|
try { |
|
|
|
list = new Y[listClassName]; |
|
|
|
// set this models id to the list |
|
modelidref = this.name + "_id"; |
|
list.set(modelidref, this.get("id")); |
|
|
|
this._relatedLists[listClassName] = list; |
|
|
|
return list; |
|
|
|
} catch (e) { |
|
Y.error("ModelList class " + listClassName + " could not be instantiated"); |
|
} |
|
|
|
return false; |
|
|
|
} |
|
|
|
|
|
}; |
|
|
|
Y.RelatedModelList = r; |
|
|
|
|
|
}, '0.0.1', { |
|
requires: ['object'] |
|
}); |