modular-backbone icon indicating copy to clipboard operation
modular-backbone copied to clipboard

How to get Router

Open sanderversluys opened this issue 14 years ago • 5 comments

Great example you've assembled here but I've wondering: what's the best practice to get the Router object from within views so I can call the .navigate function.

The router.js module returns an object with just the initialize function.

Thanks!

sanderversluys avatar Jan 11 '12 15:01 sanderversluys

Very good question, niob :).

I like the idea of holding router and other objects that should be accessible from multiple places in a global namespace object. Example project by Addy Osmani demonstrates it pretty well.

Thanks to you I pushed a commit into repository implementing this approach (see commit).

I'm very open to other opinions. AFAIK there are not many best practices about structuring Backbone.js + RequireJS applications.

kubetz avatar Jan 11 '12 16:01 kubetz

Thanks for the update! I'm using this solution right now!

Couldn't we get rid of the global object and let RequireJS inject it where needed?

sanderversluys avatar Jan 13 '12 08:01 sanderversluys

Actually - I somehow thought that when a RequireJS module is required multiple times the code inside the module is executed multiple times. So if we had a module returning our own Router object and we will require it on 2 different places (like App and a view) then it will return 2 different instances.

I created a simple test and had a look on RequireJS source code and found out it is actually caching already loaded dependencies (HERE is the code).

That is what I get when I'm just looking at examples from other people and not doing my "homework". So yes, you are right and I feel like I've learnt something obvious :).

Thanks!

kubetz avatar Jan 13 '12 09:01 kubetz

Ow cool! Doing your homework FTW!! :-)

sanderversluys avatar Jan 13 '12 09:01 sanderversluys

Indeed :).

Commit is alread in - 187048a766f0bc44ac5bc6504d7aeac236c3d101 .

Closing this issue for now. Feel free to open it if necessary. Thanks!

kubetz avatar Jan 13 '12 10:01 kubetz