Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. /**
  2. * Property Definitions can be used by Object.setProperty to define
  3. * standard object properties.
  4. *
  5. * default Property is an object property that behaves as a normal object property in
  6. * that it is enumerable, semi-typed, and can perform some action when the value is set.
  7. *
  8. * locked Property is a read only property. It cannot be changed after its been set,
  9. * however, attempting to the set the property will still trigger the callback, so that the
  10. * larger app can capture errors.
  11. */
  12.  
  13. // privateVar is the reference to the variable that actually holds the value which the property will use.
  14.  
  15. let propertyDefinitions = {
  16. defaultProperty: function (privateVar, callback) {
  17. return {
  18. enumerable: true,
  19. configurable: false,
  20. get: function () {
  21. return privateVar;
  22. },
  23. set: function (val) {
  24. // Use the type of the original variable to coerce the incoming value to that type.
  25. if(typeof(privateVar) === "number"){
  26. val = Number(val);
  27. } else if (typeof(privateVar) === "string"){
  28. val = val.toString();
  29. } else if(typeof(privateVar) === "boolean"){
  30. val = Boolean(val);
  31. }
  32. privateVar = val;
  33. if(callback && typeof callback === "function"){
  34. callback(val);
  35. }
  36. }
  37. };
  38. },
  39. lockedProperty: function (privateVar, callback) {
  40. return {
  41. enumerable: true,
  42. configurable: false,
  43. get: function () {
  44. return privateVar;
  45. },
  46. set: function (val) {
  47. // Don't change the private variable.
  48. // But, call the callback with the passed value.
  49. if(callback && typeof callback === "function"){
  50. callback(val);
  51. }
  52. }
  53. };
  54. },
  55. // Wrap content in a read-only proxy, privateVar is the object to proxy.
  56. proxy: function(privateVar){
  57. return new Proxy(privateVar, {
  58. get: function(privateVar, index){
  59. return privateVar[index];
  60. }
  61. });
  62. },
  63. // Watch a given property for a value change.
  64. // If it changes, trigger a callback.
  65. observe: function({name, value, locked=false, callback}, object){
  66. let prop = (locked === true) ?
  67. this.lockedProperty(value, callback) :
  68. this.defaultProperty(value, callback);
  69. Object.defineProperty(object, name, prop);
  70. }
  71. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement