JS trunking does not work as I expect

I think I am missing some of the fundamentals about Backbone routing functions.

I am creating an application and it looks something like this:

file: app.js

 App = {} App.nav = new Backbone.Router; require('app/controller'); 

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 do not receive the Home Activated console message.

I tried using my own routing class (i.e. Backbone.Router.extend({}) ), but I really don't see the point, since I still need to initialize it, and I want to use central history / navigation in your application, that all modules / controllers add routing to it, and do not create a router for each controller.

What am I doing wrong?

+6
source share
3 answers

http://documentcloud.github.com/backbone/#Router-navigate

From the documentation:

If you also want to call the route function, set the trigger parameter to true.

But, as OlliM wrote, you need to activate the story first!

So your answer should be:

 Backbone.history.start(); App.nav.navigate('home', {trigger: true}); 

edit: forgot to put "nav"

+15
source

For routing to work, you need to call Backbone.history.start() after setting up the routes (basically after you have done the rest). See: http://documentcloud.github.com/backbone/#History-start

+6
source

I just want to point this out, because it saved me a world of pain and heartache.

If you are directed to a user page, for example

 Backbone.router.navigate('/some/page'); // does not work 

And it does not seem to work. Add the final '/'

 Backbone.router.navigate('/some/page/'); // works 

It cost me several hours of troubleshooting ...

+1
source

Source: https://habr.com/ru/post/910060/


All Articles