583cb9dd840057ec63fc51f6e9f1a45d4f393942e3003a8ce63a2458a79f9fe9d6b8cfb2f6785d91163a2b436ba626f5cd4b0eb8211e62790b26b96dea9719 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Copyright (c) 2017 ESHA Research
  3. * Dual licensed under the MIT and GPL licenses:
  4. * http://www.opensource.org/licenses/mit-license.php
  5. * http://www.gnu.org/licenses/gpl.html
  6. *
  7. * Allows retrieval of values from within a stored object.
  8. *
  9. * store.set('foo', { is: { not: { quite: false }}});
  10. * console.log(store.get('foo.is.not.quite'));// logs false
  11. *
  12. * Status: ALPHA - currently only supports get
  13. */
  14. ;(function(_) {
  15. // save original core accessor
  16. var _get = _.get;
  17. // replace with enhanced version
  18. _.get = function(area, key, kid) {
  19. var s = _get(area, key);
  20. if (s == null) {
  21. var parts = _.split(key);
  22. if (parts) {
  23. key = parts[0];
  24. kid = kid ? parts[1] + '.' + kid : parts[1];
  25. return _.get(area, parts[0], kid);
  26. }
  27. } else if (kid) {
  28. try {
  29. var val = _.parse(s);
  30. val = _.resolvePath(val, kid);
  31. s = _.stringify(val);
  32. } catch (e) {
  33. window.console.error("Error accessing nested property:", e);
  34. return null;
  35. }
  36. }
  37. return s;
  38. };
  39. // Helper function to resolve nested paths safely
  40. _.resolvePath = function(obj, path) {
  41. return path.split('.').reduce(function(acc, key) { return acc && acc[key]; }, obj);
  42. };
  43. // expose internals on the underscore to allow extensibility
  44. _.split = function(key) {
  45. var dot = key.lastIndexOf('.');
  46. if (dot > 0) {
  47. var kid = key.substring(dot + 1, key.length);
  48. key = key.substring(0, dot);
  49. return [key, kid];
  50. }
  51. };
  52. })(window.store._);