Last active
August 29, 2015 14:06
-
-
Save ndhoule/23d309acc615f818ed87 to your computer and use it in GitHub Desktop.
getter-setter-example.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example 1 | |
*/ | |
var Proto = Object.create(HTMLElement.prototype); | |
Proto.attachedCallback = function(){ | |
// Using a generalized function is clearer and has many maintainability advantages IMHO | |
if(this.readAttributeAsJson('config-ready')){ | |
// do something | |
} | |
}; | |
Proto.readAttributeAsJson = function(name) { | |
if (!this.hasAttribute(name)) { | |
return false; | |
} | |
var attribute = this.getAttribute(name); | |
var parsed; | |
// Wrap in a try/catch block to prevent parsing errors | |
// `undefined`, malformed json, or attributes with no value will throw otherwise | |
// Could probably handle these cases better, but a try/catch is bare minimum | |
try { | |
parsed = JSON.parse(attribute); | |
} catch (e) { | |
// Ignore errors and return `undefined` | |
} | |
return parsed; | |
}; | |
document.registerElement('vs-text', { prototype: Proto }); | |
/** | |
* Example 2 | |
*/ | |
var double = (x) => x * x; | |
var a = (function() { | |
var _storage = Object.create(null); | |
return { | |
get(key) { | |
return _storage[key]; | |
}, | |
set(key, value) { | |
return _storage[key] = value; | |
} | |
}; | |
}()); | |
// consumption example | |
a.set('id', double(2)); | |
// If you really expect to set 'id' as `value * 2` every time, define a method to make | |
// transformations explicit | |
a.setId = (value) => a.set('id', double(value)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment