RequireJS - Package backbone-related modules for re-use in other Rails/JS applications

311 Views Asked by At

I am building a web application based on Rails and, on the client-side Backbone.js. For structuring my Coffeescript-Code, I used RequireJS and requirejs-rails. Each of my Backbone classes lives in its own RequireJS module.

I recently refactored a lot of code into some base classes and want to package them somehow to be able to easily reuse them in other projects (Rails and/or Javascript/Coffeescript, possible even without RequireJS) and share it on GitHub as a separate project from my Rails application. I read the RequireJS documentation on packages, but it doesn't go into the details very much. So this is what I would like to do:

  • Move my shared code into its own package, so views/base_collection_view becomes commons/views/base_collection_views and so on
  • Include the package into my requirejs-rails setup in my rails applications, and provide a compiled my-commons.js file to use within non-requirejs setups (I guess the latter would be done using almond fairly easily once I figured out how to layout the package)

A full example of a reusable RequireJS-package would really help me a lot at this point, along with some ideas how this could be transfered to requirejs-rails.

1

There are 1 best solutions below

0
On

Not sure about requirejs-rails, but with RequireJS it's pretty easy.

define(['dep1', 'dep2'] , function ($, otherLibrary) {
    return function () {
        // your module code
    };
});

Where 'dep1' and 'dep2' are other RequireJS modules that your module depends on. You can depend on as few or as many as you like. The var names you pass to the actual function ($ and otherLibrary in this example) are the names that those libraries will be assigned to within your module.

Anyone using RequireJS will be able to require your module this way, based on how the file is named and the folders it's in.

For instance, if this file was called "my-super-lib.js" inside of the libs directory, another module could just pass libs/my-super-lib to its dependency array and everything will be set up.

Update: just remembered you mentioned coffeescript. Same idea, but to be clear:

define ['dep1', 'dep2'], ($, otherLibrary) ->
    () ->
        // your module code

If you're into that. ;)