This document is intended to outline where your code should go. It's not clear from the default commonplace app structure where code should live. This document is intended to answer all questions along those lines.
I want to include a third party library.
Put it in media/js/lib/
. You may need to update main.js
to include the library in the require.config
call.
Don't forget to make sure the library is wrapped as an AMD module.
I wrote some code of my own.
I created a view.
Put it in media/js/views/
, or some subdirectory therein. views.js
will look for all views in that directory on its own.
I wrote code that handles user interactions.
If your code is relevant for only one view, put your code in the initialization section of the view (outside the function that the view returns).
If your code handles events that are not delegated and the elements that the code accesses are outside of the generated page (chrome elements, for instance), you should put your code in a common module or main.js
instead. If your code handles events that are not delegated and the elements accessed are inside the generated page, you should put your code in one of two places:
- In the returned function from the view that generates the elements. I.e.: after
builder.start()
or inbuilder.done()
. - In a helper module which is called by the returned function from the views. This is used for assigning non-delegated events on elements that are generated by more than one view. You would put the code calling out to the module in the same place as the instance above. (Note that you should prefer delegated events to this in the interest of both size and performance of your code)
I wrote more than a little bit of code.
Create a module in media/js/
. Import your module from where it's used, or if it's not used for any specific purpose, import it in main.js
.
I wrote only a little code.
Does your code expose functionality that you'd want more than one module to use? If so, create a new module and put it in main/js/
.
Does your code only consume other modules? If so, you can probably just fit your code in main.js
.
Does your code extend existing functionality in your project that isn't part of commonplace? Put your code in the original module if it makes sense. It's a common pattern to create a module, though, named foo_helpers
to complement a module named foo
. This is acceptable for making sure modules stay easily testable and maintain a suitable size.