History api statechange function script duplicates function calls each time change occurs

青春壹個敷衍的年華 提交于 2019-12-11 19:29:37

问题


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);
        });
    });

回答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){


来源:https://stackoverflow.com/questions/18634073/history-api-statechange-function-script-duplicates-function-calls-each-time-chan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!