如何将骨干路由器应用于完整路径,而不是哈希

2022-01-24 00:00:00 javascript backbone.js coffeescript

这种可能性存在吗?我们的网站不是一页的,所有的js文件都压缩在application.js里面,我可以用主干路由器来解析location.path吗?

Does that possibility exist? Our site is not one page, but all js-files compressed inside of application.js, can I use backbone router for location.path parsing?

我尝试 Backbone.history.start(pushState: true).它对我有用,但它正确吗?我只需要初始解析,而不是通过 Backbone.Router 进行复杂的路由和重定向.

I try Backbone.history.start(pushState: true). It works for me, but is it correct? I need just initial parsing, not complicated routes and redirects via Backbone.Router.

推荐答案

您可以只使用标准路由器.当您实例化它并启动历史对象时,您可以设置它应该用作其基础的根目录.在这种情况下,您似乎想使用 '/'

You can just use a standard router. When you instantiate it and start the history object you can set what the root directory it should use as its base. In this case it seems you want to to use '/'

var MyRouter = Backbone.Router.extend({
    routes: {
        "application/": "somefunc"
    }
}

var app = new MyRouter();
Backbone.history.start({pushState: true, root: '/'});

您需要设置您的网络服务器,以便在您的服务器上调用任何目录时提供您的 HTML 文件(因此骨干网,而不是 Rails,将处理您的路由).

You'll need to set your web server to serve up your HTML file whenever any directory is called on your server (so backbone, not rails, will handle your routes).

最后,在 HTML 文件中,我有一个在 Dom 就绪上运行的函数,它从 URL 中提取路径并将其传递给 navigate.

Finally, in the HTML file I have a function which runs on Dom ready and pulls the path out of the URL and passes it to navigate.

var path = location.pathname;
app.navigate(path, {trigger: true});

相关文章