Skip to content

Instantly share code, notes, and snippets.

@k33g
Created August 3, 2012 11:58
Show Gist options
  • Save k33g/3246944 to your computer and use it in GitHub Desktop.
Save k33g/3246944 to your computer and use it in GitHub Desktop.
I WANT a Backbone Controller !!!

Some times to organize my code in a backbone single page application , i miss controllers (like Playframework). So, i dit that (and i'm not ashamed ;) ...) :

Backbone.Controller = function() {};
Backbone.Controller.extend = Backbone.View.extend;

So, i can write this, now :

var myControllerOfSomething = Backbone.Controller.extend({},{

    doSomeThing : function () {
        //...
    },

    CallMeWithParameters : function (params) {
        //...
    },

    displaySomeThing : function () {
        aBackboneView.render();
    },

    doAll : function() {
        myControllerOfSomething.doSomeThing();
        myControllerOfSomething.CallMeWithParameters("hello");
        myControllerOfSomething.displaySomeThing();
    }
});

And use it :

window.RoutesManager = Backbone.Router.extend({
    routes : {

        "call/:param" : "callWithParam",
        "do" : "do"
        "*path" : "root"
    },

    root : function () { 
        myControllerOfSomething.doAll();
    },

    do : function () {
        myControllerOfSomething.doSomeThing();
    },

    display : function () { 
        myControllerOfSomething.displaySomeThing(); 
    },

    callWithParam : function (param) {
        myControllerOfSomething.CallMeWithParameters(params);
    }

});

...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment