javascript Backbone JS 路由没有按我的预期工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9581541/
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
Backbone JS Routing not working as I expect
提问by Eli
I think I'm missing some basics about Backbone's routing functions.
我想我缺少有关 Backbone 路由功能的一些基础知识。
I'm building an app and it looks something like so:
我正在构建一个应用程序,它看起来像这样:
file: app.js
file: app.js
App = {}
App.nav = new Backbone.Router;
require('app/controller');
file: controller.js
file: controller.js
App.nav.route('home', 'home', function () {
console.log("Home Activated");
});
App.navigate('home');
At this point the browser changes the URL in the address bar to /home
but nothing happens and I don't get the Home Activated
console message.
此时浏览器将地址栏中的 URL 更改为,/home
但没有任何反应,我也没有收到Home Activated
控制台消息。
I've tried using my own routing class (i.e. Backbone.Router.extend({})
) but I don't really see a point in it as I still need to initialize it, and I want to use a central history/navigation in my app that all modules/controllers add routing to it rather than creating a router for every controller.
我已经尝试使用我自己的路由类(即Backbone.Router.extend({})
),但我并没有真正看到它的意义,因为我仍然需要初始化它,并且我想在我的应用程序中使用所有模块/控制器添加的中央历史/导航路由到它而不是为每个控制器创建一个路由器。
What am I doing wrong?
我究竟做错了什么?
回答by PsyBurn
http://documentcloud.github.com/backbone/#Router-navigate
http://documentcloud.github.com/backbone/#Router-navigate
From the documentation:
从文档:
If you wish to also call the route function, set the trigger option to true.
如果您还希望调用路由功能,请将触发器选项设置为 true。
But as OlliM wrote, you need to activate the history first!
但是正如OlliM 所写,您需要先激活历史记录!
So your answer should be:
所以你的答案应该是:
Backbone.history.start();
App.nav.navigate('home', {trigger: true});
edit: forgot to put "nav"
编辑:忘了放“导航”
回答by OlliM
For the routing to work, you need to call Backbone.history.start()
after setting up your routes (basically after you've done everything else). See: http://documentcloud.github.com/backbone/#History-start
要使路由正常工作,您需要Backbone.history.start()
在设置路由后调用(基本上在完成其他所有操作后)。见:http: //documentcloud.github.com/backbone/#History-start
回答by nightsurgex2
I just want to point this out as it saved me a world of hurt and heartache.
我只想指出这一点,因为它为我节省了一个痛苦和心痛的世界。
If you are routing to a custom page such as
如果您要路由到自定义页面,例如
Backbone.router.navigate('/some/page'); // does not work
And it appears to not be working. Add a trailing '/'
它似乎不起作用。添加尾随“/”
Backbone.router.navigate('/some/page/'); // works
This cost me a few hours of troubleshooting...
这花了我几个小时的故障排除...