JavaScript getter and setters

When using web components, a common task is to read attributes from the element.

The naive way is:

var Proto = Object.create(HTMLElement.prototype);
_.extend(Proto, {
  attachedCallback: function(){
    if(this.readAttributeAsJson('config-ready')){
      //do something
    }
  },
  readAttributeAsJson : function(name) {
    if(!this.hasAttribute(name)) { return false; }
    return JSON.parse(this.getAttribute(name));
  }
});
document.registerElement('vs-text', {
  prototype: Proto
});

The better way is:

var Proto = Object.create(HTMLElement.prototype, {
  configReady: {
    get: function(){ return this.readAttributeAsJson('config-ready'); }
  }
});
_.extend(Proto, {
  attachedCallback: function(){
    if(this.configReady){
      //do something
    }
  },
  readAttributeAsJson : function(name) {
    if(!this.hasAttribute(name)) { return false; }
    return JSON.parse(this.getAttribute(name));
  }
});
document.registerElement('vs-text', {
  prototype: Proto
});

Here we are using object getter and setters.

 

Another example where if you do a.id = 1, and then try to read a.id, you get 2

var _id = null;

var a = {};
Object.defineProperty(a, "id", {
 get: function() {
 console.log("get!");
 return _id;
 },
 set: function(value) {
 console.log("set!");
 _id = 2 * value; 
 } 
}); 
Advertisements
Standard