Backgrid.js plus RequireJS

I’ve been implementing Backgrid.js into a project, and the backbone.js setup is working very nicely – I’ve managed to create a few extensions quite easily adding new reusable features.

One snag, and the author does mention this in the FAQ:

“Why doesn’t Backgrid.js support AMD?”

I am a big fanof RequireJS, and use it quite extensively in some of my larger projects. Indispensable for creating reusable code.

With RequireJS 2.x, the short answer is:  yes we can.

Simply add backgrid to your requirejs.config and shim it up:

requirejs.config({
    baseUrl: '/pub/js',
    paths: {
        backgrid: 'vendor/backgrid/backgrid'
    },
    map: {
        '*': {
            'css': 'plugins/requirecss/css'
        }
    },
    shim: {
        backgrid: {
            deps: ['jquery', 'backbone', 'underscore', 'css!vendor/backgrid/backgrid'],
            exports: 'Backgrid'
        }
    }
}

Now in a new definition, I just reference backgrid:

define(['backgrid'], function(Backgrid) {
    var CrudRow = Backgrid.Row.extend({
        ....
    });
});

and I can simply require them on demand:

require(['backgrid', 'myextension/crudrow', 'mygrid/columns', 
function(Backgrid, CrudRow, cols) {
 
    var grid = new Backgrid.Grid({
        columns: cols,
        row: CrudRow,
        ...
    });
 
    $('#content').append(grid.render().$el);
});

I’ve omitted other definitions (like jQuery and Backbone) for clarity. The css plugin is extra, and the stylesheet can be included by default otherwise. The code above is taken from an actual live project, and heavily simplified.

As for other existing Backgrid extensions, here’s how I included backgrid-select-all:

requirejs.config({
    baseUrl: '/pub/js',
    paths: {
        backgrid:		'vendor/backgrid/backgrid',
        "backgrid/select-all":	'vendor/backgrid/extensions/select-all/backgrid-select-all',
    },
    map: {
        '*': {
            'css': 'plugins/requirecss/css'
        }
    },
    shim: {
        backgrid: {
            deps: ['jquery', 'backbone', 'underscore', 'css!vendor/backgrid/backgrid'],
            exports: 'Backgrid'
        },
        "backgrid/select-all": ['backgrid', 'css!vendor/backgrid/extensions/select-all/backgrid-select-all']
    }
});