Search code examples
javascriptbackbone.jsstructure

Where to place code not directly related to a view (such as ads, analytics etc) in Backbone.js?


I am building a backbone.js application, and as far as my understanding, each backbone "class" is intended to do the following:

  • Model: the object representation of your data, ie the result of hitting an API would get stored in a model.
  • Collection: An ordered set of models, ie if you had a "book" model, you could have a collection of all models representing "science fiction" books.
  • Router: routes page URL's to actions/events, ie 'site.com/help' routes to a help: funciton(){}
  • View: The visual representation of a model, rendering to the DOM.

This leaves me uncertain as to where I should place my "generic" code, such as analytics and ad scripts, helper functions, tracking, etc.

What is the appropriate convention for these sort of things? Would I place them into a backbone view (even if they don't contain any page-renderable content)? Do I need to use a module loader like Browserify or Require.js? I would like to avoid getting those involved as the project is small and I don't need additional library overhead.


Solution

  • "What is the appropriate convention for these sort of things?"

    Splitting your code in module is a good practice. Use a module pattern or use requirejs to build modules.

    Check the module pattern here http://addyosmani.com/resources/essentialjsdesignpatterns/book/