Skip to content

Instantly share code, notes, and snippets.

@ndhoule
Last active August 29, 2015 14:06
Show Gist options
  • Save ndhoule/23d309acc615f818ed87 to your computer and use it in GitHub Desktop.
Save ndhoule/23d309acc615f818ed87 to your computer and use it in GitHub Desktop.
getter-setter-example.js
/**
* 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