History api statechange function script duplicates function calls each time change occurs
Asked Answered
I

1

0

I'm using the jquery history plugin in a simple demo that loads in a section of a specific page each time you click a nav item, what i've found though is that each time I click a new link the History.Adapter.bind(window, 'statechange', function() code is duplicated. Is it possible to unbind this every time the code has finished inside this function or can anyone advise where I may be going wrong with this?

My test page http://kylehouston.com/_testing/history/page1.html

JS

navLink.on('click', function(e) {

        e.preventDefault();

        var el = $(this);

        //get the href and remove begining /
        url = el.attr('href')
            .slice(1);

        //do a check to see if this link is already active
        if (el.hasClass('is-active')) {
            return false;
        }

        navLink.removeClass('is-active');
        el.addClass('is-active');


        History.pushState(null, null, url);


        // Bind to StateChange Event
        History.Adapter.bind(window, 'statechange', function() {
            var State = History.getState();

            mainContent.fadeOut(function() {
                $(this)
                    .empty();

                console.log('this ran');

                preloader.fadeIn();

                loadContent(mainContent, location.pathname);
            });

            History.Adapter.unbind();
        });


        //empty mainContent then empty it
        mainContent.fadeOut(function() {
            $(this)
                .empty();

            //display preloader
            preloader.fadeIn();

            //check if content already exists in pages{} if not then make call then save to pages{} or retrieve from pages{} if already exists
            loadContent(mainContent, url);
        });
    });
Imposition answered 5/9, 2013 at 10:37 Comment(0)
W
1

Have you tried to move

// Bind to StateChange Event
History.Adapter.bind(window, 'statechange', function() {
    var State = History.getState();

    mainContent.fadeOut(function() {
        $(this).empty();
        console.log('this ran');
        preloader.fadeIn();
        loadContent(mainContent, location.pathname);
    });           
});

before

navLink.on('click', function(e){
Waac answered 5/9, 2013 at 12:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.