61d6b8636f0909798c19f13d41de1cc48bea4021905280a7793a065d0024b64279ddaa87608315078c39df43607e875fb5ab0b4aa974be7ed108aba4d069a6 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. * Adds getters and setters for existing keys (and newly set() ones) to enable dot access to stored properties.
  8. *
  9. * store.dot('foo','bar');// makes store aware of keys (could also do store.set('foo',''))
  10. * store.foo = { is: true };// == store.set('foo', { is: true });
  11. * console.log(store.foo.is);// logs 'true'
  12. *
  13. * This will not create accessors that conflict with existing properties of the store object.
  14. *
  15. * Status: ALPHA - good, but ```store.foo.is=false``` won't persist while looking like it would
  16. */
  17. ;(function(_, Object, Array) {
  18. // expose internals on the underscore to allow extensibility
  19. _.dot = function(key) {
  20. var keys = !key ? this.keys() :
  21. Array.isArray(key) ? key :
  22. Array.prototype.slice.call(arguments),
  23. target = this;
  24. keys.forEach(function(key) {
  25. _.dot.define(target, key);
  26. });
  27. return this;
  28. };
  29. _.dot.define = function(target, key) {
  30. if (!(key in target)) {
  31. Object.defineProperty(target, key, {
  32. enumerable: true,
  33. get: function(){ return this.get(key); },
  34. set: function(value){ this.set(key, value); }
  35. });
  36. }
  37. };
  38. // add function(s) to the store interface
  39. _.fn('dot', _.dot);
  40. })(window.store._, window.Object, window.Array);