Search code examples
polymerpolymer-1.0polymer-starter-kit

Polymer data from router to dom-element


I started with polymer 1.0 and created a new route endpoint as mentioned below.

page('/users/:name', scrollToTop, function(data) {
      app.route = 'user-info';
      app.params = data.params;
    }); 

so if I go to users/bob it will go to route "user-info"

in my index.html the route is defined as below

<section data-route="user-info">
   <web-homepage></web-homepage>
</section>

where web-homepage is a custom element.

the custom element is as defined below

<dom-module id="web-homepage">
  <template>
    This is homepage
  </template>

  <script>
    (function() {
      'use strict';

      Polymer({
        is: 'web-homepage',
        ready:function() {
           //want to get the route parameters (eg: bob) here 
        }
      });
    })();
  </script>

</dom-module>

Is there a way to get the value route parameter ":name" i.e bob inside the ready function?


Solution

  • ready function is executed when the element is imported and created. If you access route params there, it will most likely be null/empty/undefined.

    However you can pass route params to the element as below.

    The params in app.params is the property of app. You can simply pass it to its child elements.

    index.html should look like this

    <section data-route="user-info">
       <web-homepage route-params=[[params]]></web-homepage>
    </section>
    

    Define the route-params in web-homepage

    <dom-module id="web-homepage">
      <template>
        This is homepage
      </template>
    
      <script>
        (function() {
          'use strict';
    
          Polymer({
            is: 'web-homepage',
            properties: {
              routeParams: {
                type: Object,
                observer: '_routeParamsChanged'
              }
            },
            ready:function() {
               //ready function is run during element creation. route-params will most likely be empty/null/undefined
               //Just random
               //want to get the route parameters (eg: bob) here 
            },
            _routeParamsChanged: function(newValue) {
               console.log('route params: ', newValue);
            }
          });
        })();
      </script>
    
    </dom-module>