簡體   English   中英

使用Sammy.js路由knockout.js應用程序並使用html4支持歷史記錄

[英]Routing knockout.js app with Sammy.js and history with html4 support

我剛開始玩sammy.js,我想做的第一件事就是測試歷史變化是如何運作的。 並且它按預期工作,甚至更好,但是一旦我打開IE10並切換到IE9瀏覽器模式,一切都被砍掉了。 如果我沒有使用哈希設置鏈接,IE9只會繼續關注鏈接。 當然,IE8也有同樣的問題。

此刻我只有與sammy有關的這段代碼

App.sm = $.sammy('#content', function() {

    this.get('/', function(context) {
        console.log('Yo yo yo')
    });

    this.get('/landing', function(context) {
        console.log('landing page')
    });

    this.get('/:user', function(context) {
        console.log(context)
    });

});

和發起人

$(function() {
    App.sm.run('/');
});

我還看了這個例子 ,其中包含三種類型的鏈接,普通鏈接,哈希和正常鏈接,但在IE9和IE8上正常工作。 這讓我覺得應該有可能讓sammy.js同時支持html5歷史和html4。

所以我的問題是,我怎么能做到這一點?

更新

我找到了讓它在IE上運行的方法

我剛剛添加了這個片段:

this.bind('run', function(e) {
        var ctx = this;
        $('body').on('click', 'a', function(e) {
            e.preventDefault();
            ctx.redirect($(e.target).attr('href'));
            return false;
        });
    });

無論如何,我仍然有進入網站的問題,支持瀏覽器的html5歷史記錄總是被重定向到domain.com,無論什么是初始網址。

所以我想知道我應該如何配置sammy.js來工作。 或者也許任何人都可以推薦一些與knockout.js配合得很好的其他路由器。

出於多種原因,包括搜索引擎蜘蛛和鏈接共享; 您的網站應該沒有歷史記錄API。 如果用戶看到http://example.org/poodles/red並想要在您的網站上向其他人展示紅色貴賓犬,他們會復制該鏈接。 另一位訪問者需要能夠在同一網址上看到相同的內容; 即使他們沒有在主頁開始。

出於這個原因,我建議使用History API作為漸進增強。 在可用的地方,您應該使用它來提供更好的用戶體驗。 如果它不可用,鏈接應該正常運行。

這是一個示例路由器(如Sammy),如果history.pushState不可用,它只允許默認的瀏覽器導航。

關於Knockout部分; 我在KnockoutJS項目中使用過它,效果很好。

(function($){

    function Route(path, callback) {
        function escapeRegExp(str) {
            return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
        }

        // replace "/:something" with a regular expression fragment
        var expression = escapeRegExp(path).replace(/\/:(\w+)+/g, "/(\\w+)*");

        this.regex = new RegExp(expression);
        this.callback = callback;
    }

    Route.prototype.test = function (path) {
        this.regex.lastIndex = 0;

        var match = this.regex.exec(path);

        if (match !== null && match[0].length === path.length) {
            // call it, passing any matching groups
            this.callback.apply(this, match.slice(1));
            return false;
        }

    };

    function Router(paths) {
        var self = this;
        self.routes = [];
        $.each(paths, function (path, callback) {
            self.routes.push(new Route(path, callback));
        });

        self.listen();
        self.doCallbacks(location.pathname);
    }

    Router.prototype.listen = function () {
        var self = this, $document = $(document);

        // watch for clicks on links
        // does AJAX when ctrl is not down
        // nor the href ends in .html
        // nor the href is blank
        // nor the href is /
        $document.ready(function(e){


           $document.on("click", "[href]", function(e){
               var href = this.getAttribute("href");

               if ( !e.ctrlKey && (href.indexOf(".html") !== href.length - 5) && (href.indexOf(".zip") !== href.length - 4) && href.length > 0 && href !== "/") {
                   e.preventDefault();
                   self.navigate(href);
               }
           });
        });

        window.addEventListener("popstate", function(e) {
            self.doCallbacks(location.pathname);
        });
    };

    Router.prototype.navigate = function(url) {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, url);
            this.doCallbacks(location.pathname);
        }
    };

    Router.prototype.doCallbacks = function(url) {
        var routes = this.routes;

        for (var i=0; i<routes.length; i++){
            var route = routes[i];

            // it returns false when there's a match
            if (route.test(url) === false) {
                console.log("nav matched " + route.regex);
                return;
            }
        }

        if (typeof this.fourOhFour === "function") {
            this.fourOhFour(url);
        } else {
            console.log("404 at ", url);
        }
    };

    window.Router = Router;

}).call(this, jQuery);

用法示例:

router = new Router({
    "/": function () {

    },
    "/category/:which": function (category) {

    },
    "/search/:query": function(query) {

    },
    "/search/:category/:query": function(category, query) {

    },
    "/:foo/:bar": function(foo, bar) {

    }
});

router.fourOhFour = function(requestURL){

};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM