Polymer back button doesn't work with hash routing
Asked Answered
S

1

15

Sup! Back button sometimes doesn't work with my polymer project. When i hit back button the page variable is steel the current page and i need to hit the button twice or three times to get it working for example i go to the /#/rules page from /#/home but it doesn't go back to /#/home once i press the back button the second or third time by the way it does go back to the main page. Here is my observer and router:

properties: {
    page: {
        type: String,
        reflectToAttribute: true,
        observer: '_pageChanged',
    },
},

observers: [
    '_routePageChanged(routeData.page)',
],

_routePageChanged: function (page) {
        this.page = page || 'home';
        this.set('route.path', `/${this.page}`);
},

_pageChanged: function (page) {
    // Load page import on demand. Show 404 page if fails
    var resolvedPageUrl = this.resolveUrl(page + '.html');
    this.importHref(resolvedPageUrl, null, this._showPage404, true);
    window.history.pushState({}, null, `#/${this.page}`);
},

And this is my app-route element:

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

Just can't figure out why it does not work the first time. Any help is appreciated and i have already searched a lot with no results.

Sesame answered 16/8, 2017 at 8:30 Comment(0)
C
10

Can you try this, assuming you have <app-route route="{{route}}"></app-route>?

observers: [
    '_routePageChanged(route.path)',
],

_routePageChanged: function(path) {
    if (path) {
        this.page = this.routeData.page;
    } else {
        /*
         * It's unnecessary to have the following line.
         */
        // this.page = 'home';
        this.set('route.path', '/home');
    }
},

Why it works after all?

I learned my lesson by debugging the source code of <app-route>. If the path is empty, the code for updating data will be skipped - and your observer, _routePageChanged(routeData.page), won't be triggered. See

You may consider it to be a flaw in <app-route>. Whatsoever, it's open source, and you can always find your way.

Children answered 16/8, 2017 at 13:7 Comment(4)
This is the answer ! ThanksSesame
The line, this.page = 'home';, can be omitted.Children
@PooyaRaki Thank you for pushing the question with a bounty. Please read the updated answer, and let me know if it works for you.Children
so he just ask a question, and then remove self without mark this as answer?Semifluid

© 2022 - 2024 — McMap. All rights reserved.