Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer 1.0: how to access a property value inside a function

How can I access the value of a property inside a function? Here is the property

properties:{
  name: {type: String}
}
<my-element name="Subrata"></my-element>

Inside <my-element> I have a function like this:

Approach #1

<dom-module id="my-element">
  <template>
    ...
    ...
  </template>

  <script>
  (function () {
    is: 'my-element',
    properties:{
      name: {type: String}
    },
  
    getMyName: function(){
      return this.name;
    }
  })();
  </script>
</dom-module>

My another approach was to put the value inside an element but that did not work either.

Approach #2

<dom-module id="my-element">
  <template>
    <!-- value of name is rendered OK on the page -->
    <p id="maxp">{{name}}</p>
  </template>
  
  <script>
    (function() {
      is: 'my-element',
      properties: {
        name: {type: String}
      },
      getMyName: function(){
          var maxpValue = this.$$("#maxp").innerHTML;
          return  maxpValue;
      }
    })();
  </script>
</dom-module>

How can I accomplish this? Please help.

Thanks in advance

like image 625
Subrata Sarkar Avatar asked Jun 10 '15 12:06

Subrata Sarkar


2 Answers

Instead of using a self-invoking anonymous function, you should be using the Polymer function. Change (function() { ... })(); in your code to read Polymer({ ... });.

Here's an example:

<dom-module id="my-element">
  <template>
    ...
  </template>
</dom-module>

<script>
  Polymer({
    is: 'my-element',

    properties: {
      name: {
        type: String
      }
    },

    getMyName: function() {
      return this.name;
    }
  });
</script>

I suggest that you follow the Getting Started guide from the Polymer documentation as it goes over all of this and more. It is a good starting point when you are looking to begin working with Polymer.

like image 57
Adaline Simonian Avatar answered Sep 28 '22 09:09

Adaline Simonian


You could simple do

this.name

Anywhere in any function to access the variable

like image 21
Abhay Kumar Avatar answered Sep 28 '22 09:09

Abhay Kumar