From 2681c7f0a69eaef51f335a015ccf1fb99b40bab6 Mon Sep 17 00:00:00 2001 From: lisandropuzzolo Date: Wed, 12 Jun 2013 14:53:50 -0300 Subject: [PATCH] Add normalize callback to normalize the update and create options.data If some property of your model expects to receive some type of data, for example and Object, and it receives a String or Null, mapping fails. I added the normalize callback to normalize the data before it passes to update and create callbacks. --- build/output/knockout.mapping-latest.debug.js | 49 +++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/build/output/knockout.mapping-latest.debug.js b/build/output/knockout.mapping-latest.debug.js index 00c3691..4bb0fc7 100644 --- a/build/output/knockout.mapping-latest.debug.js +++ b/build/output/knockout.mapping-latest.debug.js @@ -1,6 +1,6 @@ -/// Knockout Mapping plugin v2.4.1 -/// (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/ -/// License: MIT (http://www.opensource.org/licenses/mit-license.php) +/// Knockout Mapping plugin v2.4.1 +/// (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/ +/// License: MIT (http://www.opensource.org/licenses/mit-license.php) (function (factory) { // Module systems magic dance. @@ -303,6 +303,49 @@ } function updateViewModel(mappedRootObject, rootObject, options, parentName, parent, parentPropertyName, mappedParent) { + + //////////////////////////////////////////////////////////////////////// + /** + * example: add normalize function to your mapping definition, like create or update. + * if in your update or create callbacks you expect for example an object, and you receive + * a String, you can normalize the data using normalize callback: + * normalize: function( options ){ + * if (!$.isPlainObject( options.data ) options.data = {}; + * return options.data; + * } + * + * */ + + + var hasNormalizeCallback = function () { + return options[parentName] && options[parentName].normalize instanceof Function; + }; + + var normalizeCallback = function (obj, data) { + var params = { + data: data || rootObject, + parent: mappedParent || parent, + target: ko.utils.unwrapObservable(obj) + }; + + if (ko.isWriteableObservable(obj)) { + params.observable = obj; + } + + return options[parentName].normalize(params); + }; + + if( hasNormalizeCallback() ){ + rootObject = normalizeCallback( mappedRootObject ); + } + + //////////////////////////////////////////////////////////////////////// + + + + + + var isArray = exports.getType(ko.utils.unwrapObservable(rootObject)) === "array"; parentPropertyName = parentPropertyName || "";