From 0296e3343da0cadd55ff15bea206d0d7fe9d7dbd Mon Sep 17 00:00:00 2001 From: Marnus Weststrate Date: Wed, 19 Oct 2011 14:49:45 +0200 Subject: [PATCH] Model.attr() checks whether the property is an association and if so updates the property using its own .attrs() method. --- model/backup/backup.js | 4 ++++ model/model.js | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/model/backup/backup.js b/model/backup/backup.js index e4c8c481..5b151a26 100644 --- a/model/backup/backup.js +++ b/model/backup/backup.js @@ -105,6 +105,8 @@ See this in action: * @parent jquerymx.model.backup * Returns if the instance needs to be saved. This will go * through associations too. + * @param {Boolean} [checkAssociations] Whether attributes which are nested models or + * objects are also checked. * @return {Boolean} true if there are changes, false if otherwise */ isDirty: function(checkAssociations) { @@ -119,6 +121,8 @@ See this in action: * @function jQuery.Model.prototype.restore * @parent jquery.model.backup * restores this instance to its backup data. + * @param {Boolean} [restoreAssociations] Whether attributes which are nested models or + * objects are also restored. * @return {model} the instance (for chaining) */ restore: function(restoreAssociations) { diff --git a/model/model.js b/model/model.js index 22b3e62e..612949eb 100644 --- a/model/model.js +++ b/model/model.js @@ -1404,6 +1404,13 @@ steal('jquery/class', 'jquery/lang/string', function() { args, globalArgs, callback = success, list = Class.list; + // If the property is a nested model, assign the value(s) using its attrs method + // if the new value is an object. + if (this._isModel(property) && $.isPlainObject(value)) { + this[property].attrs( value ); + return; + } + // set the property value // notice that even if there's an error // property values get set @@ -1452,6 +1459,16 @@ steal('jquery/class', 'jquery/lang/string', function() { }, + /** + * Determine whether a property of this model is an association, i.e. another nested model. + * @hide + * @param {String} prop The property to test. + * @return {Boolean} Is it a model or not. + */ + _isModel : function(prop) { + return !!(this[prop] && this[prop].Class && this[prop].Class._models); + }, + /** * Removes an attribute from the list existing of attributes. * Each attribute is set with [jQuery.Model.prototype.attr attr]. @@ -1848,4 +1865,4 @@ steal('jquery/class', 'jquery/lang/string', function() { * - deferred - A deferred that gets resolved to any additional attrs * that might need to be set on the model instance. */ -}); \ No newline at end of file +});