SetGetWrapper
Ever deal with a framework or module that requires you to use objects with a set/get API?
Ever get stuck trying to use that opinionated object with an API that expects regular javascript objects?
Never fear, SetGetWrapper
is here. Create a wrapper object whose properties are bound to those of the set/get object, but can be accessed normally (some restrictions apply).
Note: If you have an existing object that you want to use as the wrapper, see SetGetWrapper.useAsWrapper
Example
var SetGetWrapper = // An Example class that expects you to use a set/get api{ var _secrets = {} this{ return _secretskey } this{ _secretskey = newValue }} // Introducing "Mr.SetGet"// an instance of the set/get classvar mrSetGet = // with some properties set with `set`mrSetGetmrSetGet // Introducing "Mr.Right"// a wrapper around the set get class, with a list of keys to be linkedvar mrRight = mrSetGet'age''hobbies' // mrRight can directly read and write the properties of mrSetGet, if they have been listed or discoveredmrRightage //=> 31mrRighthobbiesmrRighthobbies //=> ['knitting','knotting']// these changes affect mrSetGetmrSetGet //=> ['knitting','knotting'] // Remember: all keys must be linked before they can be used, either manually, or through discoverymrRightjob = 'accountant'mrSetGet //=> undefined, 'job' was not listed in the original list of keys to be linked // You can manually add keys to the wrapper in this way// Note: it will send all previously untracked keys' values over to mrSetGetSetGetWrappermrSetGet //=> 'accountant' // Discovery - Another way to add keys is to automatically look for unregistered keys// Note: this is equivalent to SetGetWrapper.updateKeys(mrRight,Object.keys(mrRight))// 'updateKeys' sends the existing values over to mrSetGet// To just register new bindings and ignore existing values use 'addKeys'mrRightnickname = 'sri adhikara'mrSetGet //=> undefinedSetGetWrappermrSetGet //=> 'sri adhikara' // but wait, there's more!// Introducing "Mrs.Tenured"// she's been around for a while and not about to be replaced,// but she does still need to keep in sync with mrSetGetvar mrsTenured = memories: 'plenty' files: 'many' experience: 'lots' // this will turn mrsTenured into a wrapper, send all values over to mrSetGet,// and additionally (and optionally) add another key to be linkedSetGetWrappermrSetGet //=> 'many'mrSetGet //=> undefined, not set yetmrSetGetmrsTenuredstudents //=> ['joe','carl']