【问题标题】:Routing knockout.js app with Sammy.js and history with html4 support使用 Sammy.js 路由 knockout.js 应用程序和使用 html4 支持的历史记录
【发布时间】:2013-01-22 04:35:55
【问题描述】:

我刚开始使用 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('/');
});

我还查看了这个example,它包含三种类型的链接,普通链接、哈希链接和普通链接,但在 IE9 和 IE8 上都能正常工作。这让我觉得应该可以让 sammy.js 同时支持 html5 历史记录和 html4。

所以我的问题是,我怎样才能做到这一点?

更新

我找到了让它在 IE 上运行的方法

我刚刚添加了这个sn-p:

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,无论初始 url 是什么。

所以我想知道我应该如何配置 sammy.js 才能正常工作。或者也许任何人都可以推荐 其他一些可以很好地与 knockout.js 配合使用的路由器。

【问题讨论】:

    标签: javascript knockout.js sammy.js


    【解决方案1】:

    出于多种原因,包括搜索引擎蜘蛛和链接共享;您的网站应该可以在没有 History API 的情况下运行。如果用户看到http://example.org/poodles/red 并想向其他人展示您网站上的红色贵宾犬,他们会复制链接。其他访问者需要能够在相同的 URL 上看到相同的内容;即使它们不是从首页开始。

    因此,我建议使用 History API 作为渐进式增强功能。在可用的地方,您应该使用它来提供更好的用户体验。在不可用的地方,链接应该正常工作。

    这是一个示例路由器(如 Sammy),如果 history.pushState 不可用,它只允许默认浏览器导航。

    关于淘汰赛部分;我在一个 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){
    
    };
    

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 2012-06-09
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多