• Stars
    star
    140
  • Rank 261,473 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 11 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Controller for Backbone MV*

Backbone.Controller

Build Status

Controller for Backbone MV*

Keep controller logic separated, split your routes to controllers.

Usage

DEMO: Just Test It

Usage examples:

Basic

var Controller = Backbone.Controller.extend({
  initialize: function() {
    // do init stuff
  },

  search: function(query, page) {
    // create search model and view
  }
}); 

var searchController = new Controller();

Controller supports default Backbone events

var Controller = Backbone.Controller.extend({
  initialize: function() {
    this.model = new Backbone.Model();
    this.listenTo(this.model, 'add', this._onAdd);
  },

  _onAdd: function(model) {
    // show notification view
  }
}); 

var catsController = new Controller();

Controller has remove method for cleanup

Remove method should do correct remove for all controller views and models, stop listening controller events and clear state.

var Controller = Backbone.Controller.extend({
  initialize: function() {
    this.model = new Backbone.Model();
    this.listenTo(this.model, 'add', this._onAdd);
  },

  _onAdd: function(model) {
    // show notification view
  }
}); 

var catsController = new Controller();
//...
catsController.remove();

Also remove method is calling automatically when user goes from one controller to another. See routing section for details.

Controller supports declarative routes definition.

It's little more complex than previous examples but can be used to keep all routes separately which is good idea for any size app.

var CatsController = Backbone.Controller.extend({
  routes: {
    'cats': 'list',
    'cats/:id': 'showCat'
  },

  initialize: function() {
    // do some init stuff
  },

  list: function() {
    // show cats list
  },

  showCat: function(catId) {
    // show cat view
  }
});

var DogsController = Backbone.Controller.extend({
  routes: {
    '': 'list',
    'dogs': 'list',
    'dogs/:id': 'showDog'
  },

  initialize: function() {
    // do some init stuff
  },

  list: function() {
    // show dogs list
  },

  showDog: function(catId) {
    // show cat view
  },

  remove: functin() {
    // cleanup
  }
});

var Application = Backbone.Router.extend({
  controllers: {},

  initialize: function() {
    this.controllers.cats = new CatsController({router: this});
    this.controllers.dogs = new DogsController({router: this});

    Backbone.history.start();
  }
});

The main idea - pass {router: routerInstance} as controller option. This allows to define controller specific routes in separated controllers.

When url changes from #dogs / #dogs/:id to any route which defined in another controller, remove method is calling automatically.

This case controller should clear state, remove controller specific views and models.

Controller can automatically add router without creating Backbone.Router instance

var CatsController = Backbone.Controller.extend({
  routes: {
    'cats': 'list',
    'cats/:id': 'showCat'
  },

  initialize: function() {
    // do some init stuff
  },

  list: function() {
    // show cats list
  },

  showCat: function(catId) {
    // show cat view
  }
});

var DogsController = Backbone.Controller.extend({
  routes: {
    '': 'list',
    'dogs': 'list',
    'dogs/:id': 'showDog'
  },

  initialize: function() {
    // do some init stuff
  },

  list: function() {
    // show dogs list
  },

  showDog: function(catId) {
    // show cat view
  }
});

var cats = new CatsController({router: true});
var dogs = new DogsController({router: true});

Before / after routing

Controller automatically calls onBeforeRoute / onAfterRoute functions when processing routes.

var DogsController = Backbone.Controller.extend({
  routes: {
    '': 'list',
    'dogs': 'list'
  },

  initialize: function() {
    // do some init stuff
  },

  onBeforeRoute: function(url, param1, param2, ...) {
    // called before `#dogs` / `#` routes
    // Set some state variables, create controller layout etc
  },

  onAfterRoute: function(url, param1, param2, ...) {
    // called after `#dogs` / `#` routes
  },

  list: function() {
    // show dogs list
  }
});

var dogs = new DogsController({router: true});


//Cancel route
var DogsController = Backbone.Controller.extend({
  routes: {
    'dogs': 'list',
    'dogs/:id': 'showDog'
  },

  initialize: function() {
    // do some init stuff
  },

  list: function() {
    // show dogs list
  },

  showDog: function(catId) {
    // show cat view
  },
  onBeforeRoute : function(url) {
    console.log('before route');
    var deferred = Q.defer();

    setTimeout(function() {
      deferred.resolve('ggg');
    }, 2000);

    return deferred.promise;
    //return false;
  },
  onAfterRoute : function() {
    console.log('afterRoute');
  }
});

var dogs = new DogsController({router : true});
Backbone.history.start();

Redirecting to another route

If declarative routing has been used in project, you don't have access directly to Router instance. Backbone Controller provides Controller.navigate method as proxy for Backbone.Router.navigate method.

var DogsController = Backbone.Controller.extend({
  routes: {
    'dogs': 'list'
  },

  list: function() {
    // show dogs list
    // if something
    this.navigate('cats/', {trigger: true});
  }
});

var dogs = new DogsController({router: true});

Dependencies loading

Require.js AMD

requirejs.config({
  baseUrl: 'static/',
  urlArgs: 'bust=' +  Date.now(),
  paths: {
    jquery: 'assets/js/jquery',
    underscore: 'assets/js/underscore',
    backbone: 'assets/js/backbone',
    controller: 'assets/js/backbone.controller'
  },

  shim: {
    backbone: {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone'
    },
    controller: {
      deps: ['underscore', 'backbone']
    },
    app: ['controller']
  }
});

CommonJS

var Controller = require('controller');
// or require Backbone, both fine

var HomeController = Controller.extend({
  ...
});

Old style

<script src="assets/js/jquery.js" />
<script src="assets/js/underscore.js" />
<script src="assets/js/backbone.js" />
<script src="assets/js/backbone.controller.js" />

Bower

bower install backbone.controller

More Repositories

1

d3-explorer

Exploring D3.js with React.js
JavaScript
86
star
2

mem.js

JavaScript memory management library. Works good with Backbone.js apps
JavaScript
62
star
3

backbone-package-template

Backbone.js, Require.js architecture for packages (widgets) based projects
JavaScript
28
star
4

just-test-it

Demo project for BackboneJS, Backbone.Controller and Karma + Mocha + Chai + SinonJS for unittesting
JavaScript
20
star
5

ec-deploy-mobile

Electric Deploy ReactNative iPhone app
JavaScript
10
star
6

backbone.model.state

Adds state points to your Backbone models, store and restore data.
JavaScript
8
star
7

react-data-fetching

Data fetching in React.js views example
JavaScript
7
star
8

atlantis-client

JavaScript
7
star
9

typescript-webpack-react-boilerplate

Just an example how to use those things together: TypeScript, Webpack and React
TypeScript
7
star
10

component-based-architecture

CSS
6
star
11

lets_play

JavaScript
4
star
12

react-hackathon

App for React.js hackathon (skeleton)
JavaScript
4
star
13

graphql-relay-docker-node

Docker Nodejs PostgreSQL GraphQL server setup
JavaScript
3
star
14

react-webpack-blank

Empty react webpack project
JavaScript
3
star
15

grunt-file-coffee-template

Gruntfile for CoffeeScript compilation, linting, UnitTesting and LiveReload
CoffeeScript
3
star
16

ciklum_backbonejs

JavaScript
2
star
17

react-server-render-node

Server side rendering for React.js + Node.js
JavaScript
2
star
18

global-eventemitter

Just a global instance for Node.js EventEmitter
JavaScript
2
star
19

fbooks

Books finder. Angular.js
JavaScript
1
star
20

backbone-package-example

Example for Backbone.js, Require.js package structure
JavaScript
1
star
21

react-graphql-letsplay

Demo app GraphQL, React, Flowtype
JavaScript
1
star
22

create-react-typescript-app

Exploring typescript and webpack/react
JavaScript
1
star
23

atlantis-pbem-online

Browser client for Atlantis PBEM game
JavaScript
1
star
24

cherdakjs

BackboneJS app example for CherdakJS conference
JavaScript
1
star
25

sails-nodejs-demo

Base setup for sails node.js framework for demo and investigation
JavaScript
1
star
26

board-gamers-near-you

CSS
1
star
27

atlantis-alh

Atlantis PBEM - Atlantis Little Helper (ALH) config, miskatonic ruleset
1
star