Search code examples
polymer

How do I change the route from inside a view in Polymer?


In a simple routing configuration in Polymer, like that obtained from the starter-kit:

<app-location route="{{route}}"></app-location>
<app-route
    route="{{route}}"
    pattern="/:page"
    data="{{routeData}}"
    tail="{{subroute}}"></app-route>

<app-drawer-layout fullbleed>
  <!-- Drawer content -->
  <app-drawer>
    <app-toolbar>Menu</app-toolbar>
    <iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
      <a name="view1" href="/view1">View One</a>
      <a name="view2" href="/view2">View Two</a>
      <a name="view3" href="/view3">View Three</a>
    </iron-selector>
  </app-drawer>

  <!-- Main content -->
  <app-header-layout has-scrolling-region>

    <app-header condenses reveals effects="waterfall">
      <app-toolbar>
        <paper-icon-button icon="menu" drawer-toggle></paper-icon-button>
        <div main-title>My App</div>
      </app-toolbar>
    </app-header>

    <iron-pages
        selected="[[page]]"
        attr-for-selected="name"
        fallback-selection="view404"
        role="main">
      <my-view1 name="view1"></my-view1>
      <my-view2 name="view2"></my-view2>
      <my-view3 name="view3"></my-view3>
      <my-view404 name="view404"></my-view404>
    </iron-pages>
  </app-header-layout>
</app-drawer-layout>

and a view with a button which if pressed should change the route, like this:

<dom-module id="my-view1">
  <template>
      <paper-button raised on-tap="changeRoute">Change route</paper-button>
  </template>

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

      changeRoute() {
          // How to change route here?
      }
    });
  </script>
</dom-module>

how can I change the route programmatically, in the event handler above? I tried changing window.location without success (I'm inside Electron, not sure if it's part of the problem).

From the Polymer docs, about changing routes:

Updating the route. The route object is read-write, so you can use two-way data binding or this.set to update the route. Both the route and routeData objects can be manipulated this way. For example:

this.set('route.path', '/search/');

Or:

this.set('routeData.user', 'mary');

but this is correct (and works) if done inside the main component (the one that defines the routes), while it doesn't work if called inside a view. Another way to put this question maybe is: how can I access the main router object from an inner component?


Solution

  • Your 'view1' could fire a custom event that would trigger a route change in your app.

    This would follow the observer pattern recommended in: Thinking in Polymer (The Polymer Summit 2015)

    Note: the answer to this question may also help you.