Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten long require list for backbone router

I've started a JavaScript application using Backbone.js and Require.js. The application displays different top-level views - searching items, editing different aspects of items, connecting items to each other. Each view is displayed exclusively.

The file for the router module looks like this:

define([
  'backbone',
  'myapp' 
  'views/search',
  'views/edit1', 
  'views/edit2', 
  'views/connect'], 
function(Backbone, App, SearchView, EditView1, Editview2, ConnectView) {

  return Backbone.Router.extend({
    routes: {
      "search": "doSearch",
      "edit1":  "doEdit1",
      // more routes here
    },
    doSearch: function() {
      App.main.show(new SearchView()); // Marionette.js regions
    },
    doEditView1: function() {
      App.main.show(new EditView1());
    },
    // etc.
  });
});

In my code there are much more views. Is there a way to cut down the long require list of views to one object? Maybe through another architecture or some require.js trick?

Maybe I'm too influenced by the Symfony 2 concept of what a "router" is?

like image 835
chiborg Avatar asked Nov 20 '25 07:11

chiborg


2 Answers

I've been thinking about this problem myself.

One simple solution would be to define a module with all your views in it, and then just include that as a dependency:

views/all.js

define([
  'views/search',
  'views/edit1', 
  'views/edit2', 
  'views/connect'], 
function(SearchView, EditView1, EditView2, ConnectView) {

    return {
      "EditView1": EditView1,
      "EditView2": EditView2,
      "ConnectView": ConnectView
      "SearchView": SearchView
    };
});

Then in your router module you can include views/all as a dependency assigned to a variable Views, and call any view as Views.EditView1, Views.EditView2, etc.:

define([
  'backbone',
  'myapp', 
  'views/all'], 
function(Backbone, App, Views) {
  ...

  doSearch: function() {
    App.main.show(new Views.SearchView());
  },

  ...
});

I've never actually tried this but I think it would work.

like image 72
Chris Salzberg Avatar answered Nov 22 '25 20:11

Chris Salzberg


On a syntactical level, Require.js also supports the 'simplified CommonJS wrapping'. Obviously this cannot help you avoid long lists of dependencies (as @shioyama's suggestion does) but will minimise the risk of mismatched dependency names with named function arguments and aid in keeping things tidy(er).

like image 42
biril Avatar answered Nov 22 '25 21:11

biril