javascript 如何将主干路由器应用于完整路径,而不是散列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9799977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply backbone router for full path, not a hash
提问by ValeriiVasin
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?
这种可能性存在吗?我们的网站不是一页,而是所有的js文件都压缩在里面application.js
,可以用backbone router来location.path
解析吗?
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
.
我试试Backbone.history.start(pushState: true)
。它对我有用,但它正确吗?我只需要初始解析,不需要复杂的路由和通过Backbone.Router
.
回答by tkone
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: '/'});
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).
无论何时在您的服务器上调用任何目录,您都需要设置您的 Web 服务器来提供您的 HTML 文件(因此主干,而不是 Rails,将处理您的路由)。
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
.
最后,在 HTML 文件中,我有一个函数可以在 Dom 上运行就绪并将路径从 URL 中提取出来并将其传递给navigate
.
var path = location.pathname;
app.navigate(path, {trigger: true});
回答by John Xiao
I am using this:
我正在使用这个:
window.location.href.replace(Backbone.history.getFragment(), '');
to get absolute url of backbone app's root.
获取主干应用程序根的绝对 url。
回答by iangilman
You'll need to write your own router, but fortunately that's pretty easy. Here's one I just wrote for a site I'm working on:
您需要编写自己的路由器,但幸运的是这很容易。这是我刚刚为我正在处理的网站写的一个:
var routes = {
"terms": "terms",
"privacy": "privacy",
"password-reset": "reset"
};
var path = window.location.pathname.replace("/", "");
var page = routes[path];
if (!page) {
page = "404";
}
I didn't need any of the fancy matching rules that Backbone provides, but it wouldn't be too hard to extend this idea with regular expressions. Or perhaps someone could write up a little module that uses Backbone's matching logic but doesn't do the hash/pushState redirection.
我不需要 Backbone 提供的任何花哨的匹配规则,但是用正则表达式扩展这个想法并不难。或者也许有人可以编写一个使用 Backbone 的匹配逻辑但不执行 hash/pushState 重定向的小模块。