youtube / spfjs

A lightweight JS framework for fast navigation and page updates from YouTube
https://youtube.github.io/spfjs/
MIT License
2.23k stars 147 forks source link

Deactivating / reactivating spfJS #395

Closed mrdoinel closed 8 years ago

mrdoinel commented 8 years ago

Hello! Thank you for the great spfJS!

I would like to use spfJS for my main navigation and at the same time have the ability opening/closing a modal window (that update the URL) on any page without triggering spfJS requests.

Here is what I am doing when opening the modal :

function open() {
     spf.dispose();
     // update DOM
     history.pushState({panel: true, },"Open modal", "/" + new_url);
     spf.init();
}

I also added a popstate event as follow :

window.addEventListener("popstate", function(event) {
     console.log("adress: " + document.location + ", state: " + JSON.stringify(event.state));

     if(event.state.hasOwnProperty('panel')) {
          spf.dispose();
          // open or close the panel based on the event.state
          open();
          spf.init();
     }
});

Is there a better way to momentary disable the spf postate event ? Is there a way to test if spf is active ?

(Sorry for filling a bug but I could not find any solutions based on the doc.)

anandshenoy14 commented 8 years ago

+1 to this issue want to deactivate the popstate listener in spf because have written one in my modal to behave differently

DavidCPhillips commented 8 years ago

I want to avoid scenarios where we disable the popstate listener entirely, but we could certainly make it more specific to only handle SPF events. There's already some logic which ignores history events if they don't have a state object, so what if we extend that to ignore any event without a specific spf state field such as spf-timestamp? Would that suit your needs?

mrdoinel commented 8 years ago

I managed to do what I want at the end without touching SPF code at the end and without disabling the popstate listener.

The pushState function is like that :

    function _pushState(panel_id, title, url) {
        spf.dispose();
        history.pushState({panel: true, panel_id: panel_id}, title, url);
        spf.init();
    }

And I have redefined a popstate event to capture the panel requests :

        window.addEventListener("popstate", function(event) {
            if(event.state) {
                if(event.state.hasOwnProperty('panel')) {
                    spf.dispose();

                    // do the pushState in open();
                    if(event.state.panel_id != "") open(event.state.panel_id);
                    else close();

                    spf.init();
                }
            }
        });