Search code examples
javascriptpolymerweb-componentpolymer-2.x

How to override a component's function in Polymer 2?


I'm using app-localstorage-document to store data in the browser. The documentation says to override zeroValue method to define the default value to use when there's no data stored. But I don't know how to override the component's method in Polymer. Here's what I tried but I don't think it's correct because the function is not being invoked.

<app-localstorage-document key="CatValue" data="{{cat}}"></app-localstorage-document>

class MyApp extends Polymer.Element{
   static get is(){return 'my-app';}
   static get properties(){
     return{
       cat:{
         type: String,
         value: ""
       }
     };
   }

   zeroValue(){
     this.set('cat',"a cat");
   }
}

Solution

  • This might help you:

    <app-localstorage-document key="CatValue" data="{{cat}}"></app-localstorage-document>
    
    class MyApp extends Polymer.Element{
       static get is(){return 'my-app';}
       static get properties(){
         return{
           cat:{
             type: String,
             value: function() {
                  return this.zeroValue;
             }
           }
         };
       }
    
       //Override the default method
       get zeroValue(){
         return 'a cat';
       }
    }
    

    If you do not want to override zeroValue(), it will store the value of the key CatValue as undefined.