How to avoid redundant Backbone / jQuery init with Chaplin and Browserify

114 Views Asked by At

Using Chaplin with Browserify and jQuery requires you to do the following:

Backbone = require('backbone')
$ = require('jquery')
Backbone.$ = $
Chaplin = require('chaplin')

This must be written EVERY TIME you require('chaplin'). If you miss this even once in any module that uses Chaplin and if that module is initialized first, then Chaplin will be broken because it will initialize to using Chaplin without jQuery, but later you end up setting Backbone.$ to jQuery and Chaplin is not expecting that.

An example of what this will break is Chaplin's View which will be initialized to using 'appendChild' instead of 'append' for containerMethod. But the element will be a jQuery selector which doesn't have appendChild.

Is there any way to force the order in Browserify so that this boilerplate code isn't required in every single module that uses Chaplin?

1

There are 1 best solutions below

2
joews On

You could create a module that runs your init steps and exports Chaplin.

// my-chaplin.js
var Backbone = require('backbone')
Backbone.$ = require('jquery')
module.exports = require('chaplin')

Always require this module instead of requiring chaplin directly:

// Each module in your app
var Chaplin = require('./my-chaplin');

CommonJS guarantees that this initialisation runs once, no matter how many times you require it.