knockout.mapping.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. /*!
  2. * Knockout Mapping plugin v2.5.0
  3. * (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/
  4. * License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5. */
  6. (function(factory) {
  7. 'use strict';
  8. /*jshint sub:true,curly:false*/
  9. /*global ko,require,exports,define,module*/
  10. if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
  11. // CommonJS or Node: hard-coded dependency on "knockout"
  12. factory(require("knockout"), exports);
  13. }
  14. else if (typeof define === "function" && define["amd"]) {
  15. // AMD anonymous module with hard-coded dependency on "knockout"
  16. define(["knockout", "exports"], factory);
  17. }
  18. else {
  19. // <script> tag: use the global `ko` object, attaching a `mapping` property
  20. if (typeof ko === 'undefined') {
  21. throw new Error('Knockout is required, please ensure it is loaded before loading this mapping plug-in');
  22. }
  23. factory(ko, ko.mapping = {});
  24. }
  25. }(function(ko, exports) {
  26. /*jshint sub:true,curly:false*/
  27. 'use strict';
  28. ko.mapping = exports;
  29. var DEBUG=true;
  30. var mappingProperty = "__ko_mapping__";
  31. var realKoDependentObservable = ko.dependentObservable;
  32. var mappingNesting = 0;
  33. var dependentObservables;
  34. var visitedObjects;
  35. var recognizedRootProperties = ["create", "update", "key", "arrayChanged"];
  36. var emptyReturn = {};
  37. var _defaultOptions = {
  38. include: ["_destroy"],
  39. ignore: [],
  40. copy: [],
  41. observe: []
  42. };
  43. var defaultOptions = _defaultOptions;
  44. function unionArrays() {
  45. var args = arguments,
  46. l = args.length,
  47. obj = {},
  48. res = [],
  49. i, j, k;
  50. while (l--) {
  51. k = args[l];
  52. i = k.length;
  53. while (i--) {
  54. j = k[i];
  55. if (!obj[j]) {
  56. obj[j] = 1;
  57. res.push(j);
  58. }
  59. }
  60. }
  61. return res;
  62. }
  63. function extendObject(destination, source) {
  64. var destType;
  65. for (var key in source) {
  66. if (source.hasOwnProperty(key) && source[key]) {
  67. destType = exports.getType(destination[key]);
  68. if (key && destination[key] && destType !== "array" && destType !== "string") {
  69. extendObject(destination[key], source[key]);
  70. }
  71. else {
  72. var bothArrays = exports.getType(destination[key]) === "array" && exports.getType(source[key]) === "array";
  73. if (bothArrays) {
  74. destination[key] = unionArrays(destination[key], source[key]);
  75. }
  76. else {
  77. destination[key] = source[key];
  78. }
  79. }
  80. }
  81. }
  82. }
  83. function merge(obj1, obj2) {
  84. var merged = {};
  85. extendObject(merged, obj1);
  86. extendObject(merged, obj2);
  87. return merged;
  88. }
  89. exports.isMapped = function(viewModel) {
  90. var unwrapped = ko.utils.unwrapObservable(viewModel);
  91. return unwrapped && unwrapped[mappingProperty];
  92. };
  93. exports.fromJS = function(jsObject /*, inputOptions, target*/) {
  94. if (arguments.length === 0) {
  95. throw new Error("When calling ko.fromJS, pass the object you want to convert.");
  96. }
  97. try {
  98. if (!mappingNesting) {
  99. dependentObservables = [];
  100. visitedObjects = new ObjectLookup();
  101. }
  102. mappingNesting++;
  103. var options;
  104. var target;
  105. if (arguments.length === 2) {
  106. if (arguments[1][mappingProperty]) {
  107. target = arguments[1];
  108. }
  109. else {
  110. options = arguments[1];
  111. }
  112. }
  113. if (arguments.length === 3) {
  114. options = arguments[1];
  115. target = arguments[2];
  116. }
  117. if (target) {
  118. options = merge(options, target[mappingProperty]);
  119. }
  120. options = fillOptions(options);
  121. var result = updateViewModel(target, jsObject, options);
  122. if (target) {
  123. result = target;
  124. }
  125. // Evaluate any dependent observables that were proxied.
  126. // Do this after the model's observables have been created
  127. if (!--mappingNesting) {
  128. while (dependentObservables.length) {
  129. var DO = dependentObservables.pop();
  130. if (DO) {
  131. DO();
  132. // Move this magic property to the underlying dependent observable
  133. DO.__DO["throttleEvaluation"] = DO["throttleEvaluation"];
  134. }
  135. }
  136. }
  137. // Save any new mapping options in the view model, so that updateFromJS can use them later.
  138. result[mappingProperty] = merge(result[mappingProperty], options);
  139. return result;
  140. }
  141. catch (e) {
  142. mappingNesting = 0;
  143. throw e;
  144. }
  145. };
  146. exports.fromJSON = function(jsonString /*, options, target*/) {
  147. var args = Array.prototype.slice.call(arguments, 0);
  148. args[0] = ko.utils.parseJson(jsonString);
  149. return exports.fromJS.apply(this, args);
  150. };
  151. exports.toJS = function(rootObject, options) {
  152. if (!defaultOptions) exports.resetDefaultOptions();
  153. if (arguments.length === 0) throw new Error("When calling ko.mapping.toJS, pass the object you want to convert.");
  154. if (exports.getType(defaultOptions.ignore) !== "array") throw new Error("ko.mapping.defaultOptions().ignore should be an array.");
  155. if (exports.getType(defaultOptions.include) !== "array") throw new Error("ko.mapping.defaultOptions().include should be an array.");
  156. if (exports.getType(defaultOptions.copy) !== "array") throw new Error("ko.mapping.defaultOptions().copy should be an array.");
  157. // Merge in the options used in fromJS
  158. options = fillOptions(options, rootObject[mappingProperty]);
  159. // We just unwrap everything at every level in the object graph
  160. return exports.visitModel(rootObject, function(x) {
  161. return ko.utils.unwrapObservable(x);
  162. }, options);
  163. };
  164. exports.toJSON = function(rootObject, options) {
  165. var plainJavaScriptObject = exports.toJS(rootObject, options);
  166. return ko.utils.stringifyJson(plainJavaScriptObject);
  167. };
  168. exports.defaultOptions = function() {
  169. if (arguments.length > 0) {
  170. defaultOptions = arguments[0];
  171. }
  172. else {
  173. return defaultOptions;
  174. }
  175. };
  176. exports.resetDefaultOptions = function() {
  177. defaultOptions = {
  178. include: _defaultOptions.include.slice(0),
  179. ignore: _defaultOptions.ignore.slice(0),
  180. copy: _defaultOptions.copy.slice(0),
  181. observe: _defaultOptions.observe.slice(0)
  182. };
  183. };
  184. exports.getType = function(x) {
  185. if ((x) && (typeof (x) === "object")) {
  186. if (x.constructor === Date) return "date";
  187. if (x.constructor === Array) return "array";
  188. }
  189. return typeof x;
  190. };
  191. function fillOptions(rawOptions, otherOptions) {
  192. var options = merge({}, rawOptions);
  193. // Move recognized root-level properties into a root namespace
  194. for (var i = recognizedRootProperties.length - 1; i >= 0; i--) {
  195. var property = recognizedRootProperties[i];
  196. // Carry on, unless this property is present
  197. if (!options[property]) continue;
  198. // Move the property into the root namespace
  199. if (!(options[""] instanceof Object)) options[""] = {};
  200. options[""][property] = options[property];
  201. delete options[property];
  202. }
  203. if (otherOptions) {
  204. options.ignore = mergeArrays(otherOptions.ignore, options.ignore);
  205. options.include = mergeArrays(otherOptions.include, options.include);
  206. options.copy = mergeArrays(otherOptions.copy, options.copy);
  207. options.observe = mergeArrays(otherOptions.observe, options.observe);
  208. }
  209. options.ignore = mergeArrays(options.ignore, defaultOptions.ignore);
  210. options.include = mergeArrays(options.include, defaultOptions.include);
  211. options.copy = mergeArrays(options.copy, defaultOptions.copy);
  212. options.observe = mergeArrays(options.observe, defaultOptions.observe);
  213. options.mappedProperties = options.mappedProperties || {};
  214. options.copiedProperties = options.copiedProperties || {};
  215. return options;
  216. }
  217. function mergeArrays(a, b) {
  218. if (exports.getType(a) !== "array") {
  219. if (exports.getType(a) === "undefined") a = [];
  220. else a = [a];
  221. }
  222. if (exports.getType(b) !== "array") {
  223. if (exports.getType(b) === "undefined") b = [];
  224. else b = [b];
  225. }
  226. return ko.utils.arrayGetDistinctValues(a.concat(b));
  227. }
  228. // When using a 'create' callback, we proxy the dependent observable so that it doesn't immediately evaluate on creation.
  229. // The reason is that the dependent observables in the user-specified callback may contain references to properties that have not been mapped yet.
  230. function withProxyDependentObservable(dependentObservables, callback) {
  231. var localDO = ko.dependentObservable;
  232. ko.dependentObservable = function(read, owner, options) {
  233. options = options || {};
  234. if (read && typeof read === "object") { // mirrors condition in knockout implementation of DO's
  235. options = read;
  236. }
  237. var realDeferEvaluation = options.deferEvaluation;
  238. var isRemoved = false;
  239. // We wrap the original dependent observable so that we can remove it from the 'dependentObservables' list we need to evaluate after mapping has
  240. // completed if the user already evaluated the DO themselves in the meantime.
  241. var wrap = function(DO) {
  242. // Temporarily revert ko.dependentObservable, since it is used in ko.isWriteableObservable
  243. var tmp = ko.dependentObservable;
  244. ko.dependentObservable = realKoDependentObservable;
  245. var isWriteable = ko.isWriteableObservable(DO);
  246. ko.dependentObservable = tmp;
  247. var wrapped = realKoDependentObservable({
  248. read: function() {
  249. if (!isRemoved) {
  250. ko.utils.arrayRemoveItem(dependentObservables, DO);
  251. isRemoved = true;
  252. }
  253. return DO.apply(DO, arguments);
  254. },
  255. write: isWriteable && function(val) {
  256. return DO(val);
  257. },
  258. deferEvaluation: true
  259. });
  260. if (DEBUG) wrapped._wrapper = true;
  261. wrapped.__DO = DO;
  262. return wrapped;
  263. };
  264. options.deferEvaluation = true; // will either set for just options, or both read/options.
  265. var realDependentObservable = realKoDependentObservable(read, owner, options);
  266. if (!realDeferEvaluation) {
  267. realDependentObservable = wrap(realDependentObservable);
  268. dependentObservables.push(realDependentObservable);
  269. }
  270. return realDependentObservable;
  271. };
  272. ko.dependentObservable.fn = realKoDependentObservable.fn;
  273. ko.computed = ko.dependentObservable;
  274. var result = callback();
  275. ko.dependentObservable = localDO;
  276. ko.computed = ko.dependentObservable;
  277. return result;
  278. }
  279. function updateViewModel(mappedRootObject, rootObject, options, parentName, parent, parentPropertyName, mappedParent) {
  280. var isArray = exports.getType(ko.utils.unwrapObservable(rootObject)) === "array";
  281. parentPropertyName = parentPropertyName || "";
  282. // If this object was already mapped previously, take the options from there and merge them with our existing ones.
  283. if (exports.isMapped(mappedRootObject)) {
  284. var previousMapping = ko.utils.unwrapObservable(mappedRootObject)[mappingProperty];
  285. options = merge(previousMapping, options);
  286. }
  287. var callbackParams = {
  288. data: rootObject,
  289. parent: mappedParent || parent
  290. };
  291. var hasCreateCallback = function() {
  292. return options[parentName] && options[parentName].create instanceof Function;
  293. };
  294. var createCallback = function(data) {
  295. return withProxyDependentObservable(dependentObservables, function() {
  296. if (ko.utils.unwrapObservable(parent) instanceof Array) {
  297. return options[parentName].create({
  298. data: data || callbackParams.data,
  299. parent: callbackParams.parent,
  300. skip: emptyReturn
  301. });
  302. }
  303. else {
  304. return options[parentName].create({
  305. data: data || callbackParams.data,
  306. parent: callbackParams.parent
  307. });
  308. }
  309. });
  310. };
  311. var hasUpdateCallback = function() {
  312. return options[parentName] && options[parentName].update instanceof Function;
  313. };
  314. var updateCallback = function(obj, data) {
  315. var params = {
  316. data: data || callbackParams.data,
  317. parent: callbackParams.parent,
  318. target: ko.utils.unwrapObservable(obj)
  319. };
  320. if (ko.isWriteableObservable(obj)) {
  321. params.observable = obj;
  322. }
  323. return options[parentName].update(params);
  324. };
  325. var alreadyMapped = visitedObjects.get(rootObject);
  326. if (alreadyMapped) {
  327. return alreadyMapped;
  328. }
  329. parentName = parentName || "";
  330. if (!isArray) {
  331. // For atomic types, do a direct update on the observable
  332. if (!canHaveProperties(rootObject)) {
  333. switch (exports.getType(rootObject)) {
  334. case "function":
  335. if (hasUpdateCallback()) {
  336. if (ko.isWriteableObservable(rootObject)) {
  337. rootObject(updateCallback(rootObject));
  338. mappedRootObject = rootObject;
  339. }
  340. else {
  341. mappedRootObject = updateCallback(rootObject);
  342. }
  343. }
  344. else {
  345. mappedRootObject = rootObject;
  346. }
  347. break;
  348. default:
  349. if (ko.isWriteableObservable(mappedRootObject)) {
  350. var valueToWrite;
  351. if (hasUpdateCallback()) {
  352. valueToWrite = updateCallback(mappedRootObject);
  353. mappedRootObject(valueToWrite);
  354. return valueToWrite;
  355. }
  356. else {
  357. valueToWrite = ko.utils.unwrapObservable(rootObject);
  358. mappedRootObject(valueToWrite);
  359. return valueToWrite;
  360. }
  361. }
  362. else {
  363. var hasCreateOrUpdateCallback = hasCreateCallback() || hasUpdateCallback();
  364. if (hasCreateCallback()) {
  365. mappedRootObject = createCallback();
  366. }
  367. else {
  368. mappedRootObject = ko.observable(ko.utils.unwrapObservable(rootObject));
  369. }
  370. if (hasUpdateCallback()) {
  371. mappedRootObject(updateCallback(mappedRootObject));
  372. }
  373. if (hasCreateOrUpdateCallback) return mappedRootObject;
  374. }
  375. }
  376. }
  377. else {
  378. mappedRootObject = ko.utils.unwrapObservable(mappedRootObject);
  379. if (!mappedRootObject) {
  380. if (hasCreateCallback()) {
  381. var result = createCallback();
  382. if (hasUpdateCallback()) {
  383. result = updateCallback(result);
  384. }
  385. return result;
  386. }
  387. else {
  388. if (hasUpdateCallback()) {
  389. //Removed ambiguous parameter result
  390. return updateCallback();
  391. }
  392. mappedRootObject = {};
  393. }
  394. }
  395. if (hasUpdateCallback()) {
  396. mappedRootObject = updateCallback(mappedRootObject);
  397. }
  398. visitedObjects.save(rootObject, mappedRootObject);
  399. if (hasUpdateCallback()) return mappedRootObject;
  400. // For non-atomic types, visit all properties and update recursively
  401. visitPropertiesOrArrayEntries(rootObject, function(indexer) {
  402. var fullPropertyName = parentPropertyName.length ? parentPropertyName + "." + indexer : indexer;
  403. if (ko.utils.arrayIndexOf(options.ignore, fullPropertyName) !== -1) {
  404. return;
  405. }
  406. if (ko.utils.arrayIndexOf(options.copy, fullPropertyName) !== -1) {
  407. mappedRootObject[indexer] = rootObject[indexer];
  408. return;
  409. }
  410. if (typeof rootObject[indexer] !== "object" && exports.getType(rootObject[indexer]) !== "array" && options.observe.length > 0 && ko.utils.arrayIndexOf(options.observe, fullPropertyName) === -1) {
  411. mappedRootObject[indexer] = rootObject[indexer];
  412. options.copiedProperties[fullPropertyName] = true;
  413. return;
  414. }
  415. // In case we are adding an already mapped property, fill it with the previously mapped property value to prevent recursion.
  416. // If this is a property that was generated by fromJS, we should use the options specified there
  417. var prevMappedProperty = visitedObjects.get(rootObject[indexer]);
  418. var retval = updateViewModel(mappedRootObject[indexer], rootObject[indexer], options, indexer, mappedRootObject, fullPropertyName, mappedRootObject);
  419. var value = prevMappedProperty || retval;
  420. if (options.observe.length > 0 && ko.utils.arrayIndexOf(options.observe, fullPropertyName) === -1) {
  421. mappedRootObject[indexer] = ko.utils.unwrapObservable(value);
  422. options.copiedProperties[fullPropertyName] = true;
  423. return;
  424. }
  425. if (ko.isWriteableObservable(mappedRootObject[indexer])) {
  426. value = ko.utils.unwrapObservable(value);
  427. if (mappedRootObject[indexer]() !== value) {
  428. mappedRootObject[indexer](value);
  429. }
  430. }
  431. else {
  432. value = mappedRootObject[indexer] === undefined ? value : ko.utils.unwrapObservable(value);
  433. mappedRootObject[indexer] = value;
  434. }
  435. options.mappedProperties[fullPropertyName] = true;
  436. });
  437. }
  438. }
  439. else { //mappedRootObject is an array
  440. var changes = [];
  441. var hasKeyCallback = false;
  442. var keyCallback = function(x) {
  443. return x;
  444. };
  445. if (options[parentName] && options[parentName].key) {
  446. keyCallback = options[parentName].key;
  447. hasKeyCallback = true;
  448. }
  449. if (!ko.isObservable(mappedRootObject)) {
  450. // When creating the new observable array, also add a bunch of utility functions that take the 'key' of the array items into account.
  451. mappedRootObject = ko.observableArray([]);
  452. mappedRootObject.mappedRemove = function(valueOrPredicate) {
  453. var predicate = typeof valueOrPredicate === "function" ? valueOrPredicate : function(value) {
  454. return value === keyCallback(valueOrPredicate);
  455. };
  456. return mappedRootObject.remove(function(item) {
  457. return predicate(keyCallback(item));
  458. });
  459. };
  460. mappedRootObject.mappedRemoveAll = function(arrayOfValues) {
  461. var arrayOfKeys = filterArrayByKey(arrayOfValues, keyCallback);
  462. return mappedRootObject.remove(function(item) {
  463. return ko.utils.arrayIndexOf(arrayOfKeys, keyCallback(item)) !== -1;
  464. });
  465. };
  466. mappedRootObject.mappedDestroy = function(valueOrPredicate) {
  467. var predicate = typeof valueOrPredicate === "function" ? valueOrPredicate : function(value) {
  468. return value === keyCallback(valueOrPredicate);
  469. };
  470. return mappedRootObject.destroy(function(item) {
  471. return predicate(keyCallback(item));
  472. });
  473. };
  474. mappedRootObject.mappedDestroyAll = function(arrayOfValues) {
  475. var arrayOfKeys = filterArrayByKey(arrayOfValues, keyCallback);
  476. return mappedRootObject.destroy(function(item) {
  477. return ko.utils.arrayIndexOf(arrayOfKeys, keyCallback(item)) !== -1;
  478. });
  479. };
  480. mappedRootObject.mappedIndexOf = function(item) {
  481. var keys = filterArrayByKey(mappedRootObject(), keyCallback);
  482. var key = keyCallback(item);
  483. return ko.utils.arrayIndexOf(keys, key);
  484. };
  485. mappedRootObject.mappedGet = function(item) {
  486. return mappedRootObject()[mappedRootObject.mappedIndexOf(item)];
  487. };
  488. mappedRootObject.mappedCreate = function(value) {
  489. if (mappedRootObject.mappedIndexOf(value) !== -1) {
  490. throw new Error("There already is an object with the key that you specified.");
  491. }
  492. var item = hasCreateCallback() ? createCallback(value) : value;
  493. if (hasUpdateCallback()) {
  494. var newValue = updateCallback(item, value);
  495. if (ko.isWriteableObservable(item)) {
  496. item(newValue);
  497. }
  498. else {
  499. item = newValue;
  500. }
  501. }
  502. mappedRootObject.push(item);
  503. return item;
  504. };
  505. }
  506. var currentArrayKeys = filterArrayByKey(ko.utils.unwrapObservable(mappedRootObject), keyCallback).sort();
  507. var newArrayKeys = filterArrayByKey(rootObject, keyCallback);
  508. if (hasKeyCallback) newArrayKeys.sort();
  509. var editScript = ko.utils.compareArrays(currentArrayKeys, newArrayKeys);
  510. var ignoreIndexOf = {};
  511. var i, j, key;
  512. var unwrappedRootObject = ko.utils.unwrapObservable(rootObject);
  513. var itemsByKey = {};
  514. var optimizedKeys = true;
  515. for (i = 0, j = unwrappedRootObject.length; i < j; i++) {
  516. key = keyCallback(unwrappedRootObject[i]);
  517. if (key === undefined || key instanceof Object) {
  518. optimizedKeys = false;
  519. break;
  520. }
  521. itemsByKey[key] = unwrappedRootObject[i];
  522. }
  523. var newContents = [];
  524. var passedOver = 0;
  525. var item, index;
  526. for (i = 0, j = editScript.length; i < j; i++) {
  527. key = editScript[i];
  528. var mappedItem;
  529. var fullPropertyName = parentPropertyName + "[" + i + "]";
  530. switch (key.status) {
  531. case "added":
  532. item = optimizedKeys ? itemsByKey[key.value] : getItemByKey(ko.utils.unwrapObservable(rootObject), key.value, keyCallback);
  533. mappedItem = updateViewModel(undefined, item, options, parentName, mappedRootObject, fullPropertyName, parent);
  534. if (!hasCreateCallback()) {
  535. mappedItem = ko.utils.unwrapObservable(mappedItem);
  536. }
  537. index = ignorableIndexOf(ko.utils.unwrapObservable(rootObject), item, ignoreIndexOf);
  538. if (mappedItem === emptyReturn) {
  539. passedOver++;
  540. }
  541. else {
  542. newContents[index - passedOver] = mappedItem;
  543. }
  544. ignoreIndexOf[index] = true;
  545. break;
  546. case "retained":
  547. item = optimizedKeys ? itemsByKey[key.value] : getItemByKey(ko.utils.unwrapObservable(rootObject), key.value, keyCallback);
  548. mappedItem = getItemByKey(mappedRootObject, key.value, keyCallback);
  549. updateViewModel(mappedItem, item, options, parentName, mappedRootObject, fullPropertyName, parent);
  550. index = ignorableIndexOf(ko.utils.unwrapObservable(rootObject), item, ignoreIndexOf);
  551. newContents[index] = mappedItem;
  552. ignoreIndexOf[index] = true;
  553. break;
  554. case "deleted":
  555. mappedItem = getItemByKey(mappedRootObject, key.value, keyCallback);
  556. break;
  557. }
  558. changes.push({
  559. event: key.status,
  560. item: mappedItem
  561. });
  562. }
  563. mappedRootObject(newContents);
  564. if (options[parentName] && options[parentName].arrayChanged) {
  565. ko.utils.arrayForEach(changes, function(change) {
  566. options[parentName].arrayChanged(change.event, change.item);
  567. });
  568. }
  569. }
  570. return mappedRootObject;
  571. }
  572. function ignorableIndexOf(array, item, ignoreIndices) {
  573. for (var i = 0, j = array.length; i < j; i++) {
  574. if (ignoreIndices[i] === true) continue;
  575. if (array[i] === item) return i;
  576. }
  577. return null;
  578. }
  579. function mapKey(item, callback) {
  580. var mappedItem;
  581. if (callback) mappedItem = callback(item);
  582. if (exports.getType(mappedItem) === "undefined") mappedItem = item;
  583. return ko.utils.unwrapObservable(mappedItem);
  584. }
  585. function getItemByKey(array, key, callback) {
  586. array = ko.utils.unwrapObservable(array);
  587. for (var i = 0, j = array.length; i < j; i++) {
  588. var item = array[i];
  589. if (mapKey(item, callback) === key) return item;
  590. }
  591. throw new Error("When calling ko.update*, the key '" + key + "' was not found!");
  592. }
  593. function filterArrayByKey(array, callback) {
  594. return ko.utils.arrayMap(ko.utils.unwrapObservable(array), function(item) {
  595. if (callback) {
  596. return mapKey(item, callback);
  597. }
  598. else {
  599. return item;
  600. }
  601. });
  602. }
  603. function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
  604. if (exports.getType(rootObject) === "array") {
  605. for (var i = 0; i < rootObject.length; i++)
  606. visitorCallback(i);
  607. }
  608. else {
  609. for (var propertyName in rootObject) {
  610. if (rootObject.hasOwnProperty(propertyName)) {
  611. visitorCallback(propertyName);
  612. }
  613. }
  614. }
  615. }
  616. function canHaveProperties(object) {
  617. var type = exports.getType(object);
  618. return ((type === "object") || (type === "array")) && (object !== null);
  619. }
  620. // Based on the parentName, this creates a fully classified name of a property
  621. function getPropertyName(parentName, parent, indexer) {
  622. var propertyName = parentName || "";
  623. if (exports.getType(parent) === "array") {
  624. if (parentName) {
  625. propertyName += "[" + indexer + "]";
  626. }
  627. }
  628. else {
  629. if (parentName) {
  630. propertyName += ".";
  631. }
  632. propertyName += indexer;
  633. }
  634. return propertyName;
  635. }
  636. exports.visitModel = function(rootObject, callback, options) {
  637. options = options || {};
  638. options.visitedObjects = options.visitedObjects || new ObjectLookup();
  639. var mappedRootObject;
  640. var unwrappedRootObject = ko.utils.unwrapObservable(rootObject);
  641. if (!canHaveProperties(unwrappedRootObject)) {
  642. return callback(rootObject, options.parentName);
  643. }
  644. else {
  645. options = fillOptions(options, unwrappedRootObject[mappingProperty]);
  646. // Only do a callback, but ignore the results
  647. callback(rootObject, options.parentName);
  648. mappedRootObject = exports.getType(unwrappedRootObject) === "array" ? [] : {};
  649. }
  650. options.visitedObjects.save(rootObject, mappedRootObject);
  651. var parentName = options.parentName;
  652. visitPropertiesOrArrayEntries(unwrappedRootObject, function(indexer) {
  653. if (options.ignore && ko.utils.arrayIndexOf(options.ignore, indexer) !== -1) return;
  654. var propertyValue = unwrappedRootObject[indexer];
  655. options.parentName = getPropertyName(parentName, unwrappedRootObject, indexer);
  656. // If we don't want to explicitly copy the unmapped property...
  657. if (ko.utils.arrayIndexOf(options.copy, indexer) === -1) {
  658. // ...find out if it's a property we want to explicitly include
  659. if (ko.utils.arrayIndexOf(options.include, indexer) === -1) {
  660. // The mapped properties object contains all the properties that were part of the original object.
  661. // If a property does not exist, and it is not because it is part of an array (e.g. "myProp[3]"), then it should not be unmapped.
  662. if (unwrappedRootObject[mappingProperty] &&
  663. unwrappedRootObject[mappingProperty].mappedProperties && !unwrappedRootObject[mappingProperty].mappedProperties[indexer] &&
  664. unwrappedRootObject[mappingProperty].copiedProperties && !unwrappedRootObject[mappingProperty].copiedProperties[indexer] && (exports.getType(unwrappedRootObject) !== "array")) {
  665. return;
  666. }
  667. }
  668. }
  669. switch (exports.getType(ko.utils.unwrapObservable(propertyValue))) {
  670. case "object":
  671. case "array":
  672. case "undefined":
  673. var previouslyMappedValue = options.visitedObjects.get(propertyValue);
  674. mappedRootObject[indexer] = (exports.getType(previouslyMappedValue) !== "undefined") ? previouslyMappedValue : exports.visitModel(propertyValue, callback, options);
  675. break;
  676. default:
  677. mappedRootObject[indexer] = callback(propertyValue, options.parentName);
  678. }
  679. });
  680. return mappedRootObject;
  681. };
  682. function SimpleObjectLookup() {
  683. var keys = [];
  684. var values = [];
  685. this.save = function(key, value) {
  686. var existingIndex = ko.utils.arrayIndexOf(keys, key);
  687. if (existingIndex >= 0) values[existingIndex] = value;
  688. else {
  689. keys.push(key);
  690. values.push(value);
  691. }
  692. };
  693. this.get = function(key) {
  694. var existingIndex = ko.utils.arrayIndexOf(keys, key);
  695. var value = (existingIndex >= 0) ? values[existingIndex] : undefined;
  696. return value;
  697. };
  698. }
  699. function ObjectLookup() {
  700. var buckets = {};
  701. var findBucket = function(key) {
  702. var bucketKey;
  703. try {
  704. bucketKey = key;//JSON.stringify(key);
  705. }
  706. catch (e) {
  707. bucketKey = "$$$";
  708. }
  709. var bucket = buckets[bucketKey];
  710. if (bucket === undefined) {
  711. bucket = new SimpleObjectLookup();
  712. buckets[bucketKey] = bucket;
  713. }
  714. return bucket;
  715. };
  716. this.save = function(key, value) {
  717. findBucket(key).save(key, value);
  718. };
  719. this.get = function(key) {
  720. return findBucket(key).get(key);
  721. };
  722. }
  723. }));