How could I use Router in View module in modular Backbone.js app?
backbone-routing, backbone.js, requirejs
Solution
Create a separate module that is included in every other module you use -- it will simply create an object you can use to attach the router instance and call it from any view or module you wish later on. (in addition to other things like store data and pass around to other modules easily)
Include this module in the router module you have pasted first here. Remove the start function from the bottom of your router module. And just return AppRouter at the end of that file.
In your app module where you end up starting backbone and creating the router, you can saved the router initialization to that shared object I was referring to.
IE,
shared.js -> no deps, but creates YourObject = {}; and returns YourObject router.js -> has shared.js included app.js -> has shared.js included and router.js. app sets up router and saves to YourObject.router then starts backbone. You can now call YourObject.router.navigate() from any other module where you require this shared.js module
Problem
I use RequireJS to organize my Backbone app and my Router module is as follows: ``` define([ 'jquery', 'underscore', 'backbone', 'collections/todos', 'views/todosview' ], function($, _, Backbone, TodosCollection, TodosView){ var AppRouter = Backbone.Router.extend({ routes: { "": "index", "category/:name": "hashcategory" }, initialize: function(options){ // Do something }, index: function(){ // Do something }, hashcategory: function(name){ // Do something } }); var start = function(){ p = $.ajax({ url: 'data/todolist.json', dataType: 'json', data: {}, success: function(data) { var approuter = new AppRouter({data: data}); Backbone.history.start(); } }); }; return { start: start }; }); ``` And I have another `app` module which uses `Router.start()` to trigger the whole app. Now, in my Backbone.View module, I want to use `Router.navigate` to trigger the route in this `Router` module. The starting part of my View module is as follows: ``` define([ 'jquery', 'underscore', 'backbone', 'models/todo', 'views/todoview', 'text!templates/todo.html', 'router' ], function($, _, Backbone, TodoModel, TodoView, todoTemplate, Router){... ``` But when I want to use `Router` in this module, it always says `Router is not defined`. What I want to do is to call `Router.navigate` when some action is fired in this View module. So how could I achieve this?