Skip to content

Instantly share code, notes, and snippets.

@alecperkins
Created December 11, 2012 22:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alecperkins/4263031 to your computer and use it in GitHub Desktop.
Save alecperkins/4263031 to your computer and use it in GitHub Desktop.
CoffeeScript-friendly Backbone.Marionette module definition pattern.
# Since CoffeeScript wraps everything in a closure by default, the module
# definition function pattern that Marionette normally uses is unnecessary.
# (And cumbersome with having to indent everything.) Instead, creating the
# module at the very begining makes it available to everything in the file, and
# the initializers and exported classes can be added at the end of the file.
# (This relies on things like the App and Backbone being on window, but they
# already have to be for CoffeeScript-based code to work.)
# Create the module.
Foo = App.module 'Foo'
# or a submodule
Baz = App.module 'Bar.Baz'
# ... module definition code ...
# Add initializer functions.
Foo.addInitializer ->
Foo.controller = new FooController()
# Attach classes that need to be "exported" to module.
Foo.SomeClass = SomeClass
# Exporting like that can be a little repetitive. Adding an export method to
# the module prototype helps alleviate this. (Requires named functions as
# generated by CoffeeScript's classes.)
# Add this after Marionette is loaded but before your modules are defined.
Marionette.Module::export = (args...) ->
for arg in args
@[arg.name] = arg
return this
# Now, instead of doing the repetitive...
Foo.SomeClass = SomeClass
Foo.OtherClass = OtherClass
# ...the classes can be exported using `.export`:
Foo.export SomeClass, OtherClass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment