Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: Where do I put my jQuery setup?

I'm getting to grips with Backbone.js, but one thing I don't understand is where to put all the one-off jQuery code I need to set up my page.

You know the sort of thing: configuring a jQuery carousel plugin, adding a 'scroll to top' arrow... the one-off configuration that happens when the user first loads the page.

At the moment I'm doing it in my Router:

 var AppRouter = Backbone.Router.extend({
  routes: {
    // some routes
  },
  initialize: function() {
    initializeJqueryStuff();
  } ...
 });
 var StateApp = new AppRouter();
 Backbone.history.start({
   pushState: true
 });
 function initializeJqueryStuff() { 
   // one-off jQuery stuff goes here
 }

Yeuch. How should I be doing it? Should initializeJqueryStuff be another property of the Router object? Should it all just live inside initialize? Or should I actually keep this code completely separate from the Backbone app?

like image 903
Richard Avatar asked Feb 01 '13 09:02

Richard


1 Answers

I typically define a LayoutView, i.e. a root view which is responsible for rendering all the "actual" views in the application. This layout view is only initialized once, before any other view code needs to run. It's also where I tend to do any one-off view configurations.

Sample:

//LayoutView should be considered a singleton, only initialized once
var LayoutView = Backbone.View.extend({
    el:'body',

    initialize: function() {
        this.initializeSomejQueryStuff();
    },

    renderChild: function(child) {
        if(this._currentChild)
            this._currentChild.remove();
        this._currentChild = child;
        this.$el.html(child.render().el);
    },

    initializeSomejQueryStuff: function() {
        //init here
    }
});

Usage:

var AppRouter = Backbone.Router.extend({
    routes: {
        "foo/:id": "foo"
    },

    initialize: function() {
        this.layout = new LayoutView();
    },

    foo: function(id) {
        var model = new Foo({id:id});
        var view = new FooView({model:model});

        //delegate the view rendering to a layout
        this.layout.renderChild(view);
    }
});
like image 180
jevakallio Avatar answered Nov 16 '22 23:11

jevakallio