Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Property Definitions can be used by Object.setProperty to define
- * standard object properties.
- *
- * default Property is an object property that behaves as a normal object property in
- * that it is enumerable, semi-typed, and can perform some action when the value is set.
- *
- * locked Property is a read only property. It cannot be changed after its been set,
- * however, attempting to the set the property will still trigger the callback, so that the
- * larger app can capture errors.
- */
- // privateVar is the reference to the variable that actually holds the value which the property will use.
- let propertyDefinitions = {
- defaultProperty: function (privateVar, callback) {
- return {
- enumerable: true,
- configurable: false,
- get: function () {
- return privateVar;
- },
- set: function (val) {
- // Use the type of the original variable to coerce the incoming value to that type.
- if(typeof(privateVar) === "number"){
- val = Number(val);
- } else if (typeof(privateVar) === "string"){
- val = val.toString();
- } else if(typeof(privateVar) === "boolean"){
- val = Boolean(val);
- }
- privateVar = val;
- if(callback && typeof callback === "function"){
- callback(val);
- }
- }
- };
- },
- lockedProperty: function (privateVar, callback) {
- return {
- enumerable: true,
- configurable: false,
- get: function () {
- return privateVar;
- },
- set: function (val) {
- // Don't change the private variable.
- // But, call the callback with the passed value.
- if(callback && typeof callback === "function"){
- callback(val);
- }
- }
- };
- },
- // Wrap content in a read-only proxy, privateVar is the object to proxy.
- proxy: function(privateVar){
- return new Proxy(privateVar, {
- get: function(privateVar, index){
- return privateVar[index];
- }
- });
- },
- // Watch a given property for a value change.
- // If it changes, trigger a callback.
- observe: function({name, value, locked=false, callback}, object){
- let prop = (locked === true) ?
- this.lockedProperty(value, callback) :
- this.defaultProperty(value, callback);
- Object.defineProperty(object, name, prop);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement