When I began work on the newest incarnation of Ninja Forms, I decided that I was going to use RequireJS and the AMD design pattern for the front-end. (The anonymous module definition pattern is deserving of its own post, so we’ll come back to that another day.) One of the cruxes of my design was Backbone Radio, a plugin for Backbone that lets you create a message bus in your app. I grabbed a copy of the Radio plugin and began hacking away. I ran into a problem pretty quickly, however, when Backbone Radio began trying to load Backbone and Underscore as modules through RequireJS.

The Problem With RequireJS


If you’re working with a JS library and it’s included with WordPress by default, you should use the copy bundled with WordPress. This helps to make sure that any plugins using these resources are on the same version and avoiding as many conflicts as possible. Most developers have probably experienced the mess that can result from enqueuing multiple versions of jQuery or another popular JS library. As I said, using the versions of Backbone and Underscore included with WordPress presented a problem with Backbone Radio, which was attempting to load Backbone and Underscore as modules. It was looking for files named “backbone.js” and “underscore.js” within my application. Of course, I didn’t have these files, because I was simply enqueuing the libraries within WordPress.

The Solution

After banging my head against the wall for much longer than I care to divulge, I came up with a very simple solution. I created two module definition files, named backbone.js and underscore.js, and saved them in my project. Rather than including a new version of Backbone and Underscore, I returned the definitions that were already added to the page by WordPress. You can see examples of these files below. Hopefully this experience will be helpful to those trying to get RequireJS and Backbone Radio working within WordPress.