SlideShare a Scribd company logo
Modules in JavaScript
Or How to Break Your Code
(Into Little Pieces)
A Talk by Michael Cordingley
Module Types
●

Modules are sometimes
misunderstood
–

●

File Modules
–

Confusion in naming

Each piece of code to
its own file

They come in different
flavors
–

File

–
●

●

Logical

In an ideal world, the two
overlap 1:1

●

Logical Modules
–

Each piece of code to
its own predictable code
location
The Cost of Structure
Three different difficulty
levels
–

Different trade-offs of
fixed versus variable
costs

Complexity vs. Scale

Project Complexity

●

Project Scale

Simple

Moderate

Complex
File Modules
●

Break your code out into separate files
–

●

●

Ideally, one file per idea

Files should be small and logically arranged on the filesystem
Don't forget about production!
–

Files need to be concatenated and minified as part of
your build process.
File Modules – Simple
●

●

If a project uses very little JavaScript, throw it it all into a
single file for each page.
Didn't you just say one idea per file?
–

●

It's more maintainable to have everything in one place, if that
place isn't too cluttered.
–

●

I lied.

We only need organization schemes when we have too
much.

When starting a new project, START WITH THIS ONE unless
you have good reason to do otherwise!
File Modules – Moderate
●

Break code out into separate files and load them each with
a script tag.
–

●

Don't forget to bundle these into a single file that gets
loaded as a giant blob for production

Doesn't this get hard to keep up with all of the
dependencies?
–

Only if you have several files

–

Most projects never reach that scale
Transitioning to Moderation
●

●

It isn't a clean break
Just start pulling your nouns out into separate files as your
project acquires them
–
–

●

These are probably reusable across pages anyway
Pulling them out also encourages you to write a clean
interface

If you page script exceeds 200 lines, you probably have
lurking nouns, or at least some code that could be DRYed
out.
–

Please don't wait this long!
File Modules – Complex
●

So you went for the moderate route and now you're
drowning in files?
–

●

Time to level up.

Pull in a formalized way to load and compile files
–

require.js

–

yepnope.js

–

etc.
Caveat Emptor
●

Things like require.js are geared more for single-page
apps than for multi-page apps
–

Most of your projects are probably multi-page apps

–

You're probably only drowning in JS files if you have a
single-page app

–

require.js becomes painful very quickly if you want to
use it on a multi-page app
Transitioning to Complexity
●

●

●

Update your file module to conform to your module-loader
of choice
Update every usage of that module to be loaded with the
module-loader
Don't forget the whole concatenation/minification thing
–

This is where the pain ramps up

–

You need to define blobs
●

Separate bundlings of code that load together
File Modules in the Future
●

ECMAScript 6 (Harmony) will bring native modules to the
language
–

Shim:
https://github.com/ModuleLoader/es6-module-loader

–

Despite the shim, this is not yet ready for general
consumption
●

The spec isn't finished yet
Logical Modules
●

Where do your objects, functions, and variables all live?
–

Hint: Not in the global namespace.

–

I'm not lying this time!
Logical Modules – Simple
●

Just keep 'em in your page script
–

●

If you haven't broken it out into its own file anyway, it
probably isn't very big or very complicated

Pull it out into a logical module at the same time that you'd
pull it out into a file module and for the same reasons
Logical Modules – Moderate
●

OK, so it's out into its own file
–

Don't make it a global!

–

Projects get cluttered this way
It needs a home that is globally-accessible
●

●
●

It may be an object that you reuse across pages
It may be repeated functionality
– Like enhancing your site navigation
Introducing the Application Object
●

Make a global
–
–

●

But only one!
For now, it's just an object literal

Call it “App” or the name of your project: “FooBarFighters”
–

No, I'm not actually familiar with their music

–

Yes, the puns are always intentional, even when bad
Application Object – Continued
●

Attach your modules to this object
–
–

●

e.g. App.Navigation, App.Forms, App.InstantiableObject
Submodules go as properties on their parent modules

If your module needs initialization, add an “init” or
“initialize” method to it.
–
–

●

e.g. App.Navigation.initialize();
This is responsible for calling submodule intializers

If you have modules that need initialization, also have an
“App.initialize();” method that gets called on DOM ready
Application Object – Finish
●

This application object can and should be broken out across
multiple files.
–

The “App.initialize()” method saves you from having to
worry about the order in which they load

The Application object just comes first
Don't forget about “this”
●

●

–

Useful to avoid having to bake the full module name into
functions that use other functions

–

e.g. Inside of “App.Navigation.initialize()” “this” is
“App.Navigation”
The Catch
●

“This is great! Everything is cleanly separated out into its own
place, but I need to load a module after the page load and
then initialize it.”
–

●

“Oh yeah, and I don't know if it'll have loaded before the
Application starts or not.”
–

●

OK.

Um, K.

“And this other piece needs to run only (before|after) the rest
is all set up.”
–

…why are you doing this to me?
Logical Modules – Complex
●

Introducing the Application object!
–

●

But this time, it's a real, instantiated object

“var App = new Application();”
–

You could write the definition of “Application” yourself,
but it's best not to

–

We'll get to that
The New Application Object
●

When a new module gets loaded after the application has
started, this will automatically start it.
–

●

Otherwise, it'll wait until the application starts

It also publishes events
–

–
●

So you can run code just before and just after the
application starts
It even doubles as a free event bus

The modules also get events
–

Same deal as the Application
And where do I get this?
●

What, you don't want to reinvent the wheel?
–

●

Fine, here it is:
https://github.com/marionettejs/backbone.marionette/blob/m

“But, I don't use or want Underscore, Backbone, and the
whole rest of Marionette!”
–

Jeez, you're picky.

–

https://github.com/mcordingley/Appliance
The End Goal
●

Reduce complexity
–

Whenever you introduce a new organizational tool,
make sure it reduces project complexity

–

Use the simplest scheme you can get away with

–

Make things as easy as possible for anyone who has to
maintain your code after you've left it behind
Thank You
●

This talk can be found in article format at:
–

http://michaelcordingley.me/articles/when-spaghetti-overflow

More Related Content

What's hot

Untangling - fall2017 - week 7
Untangling - fall2017 - week 7Untangling - fall2017 - week 7
Untangling - fall2017 - week 7
Derek Jacoby
 
Writing Effective Self-Help Guides for World Domination
Writing Effective Self-Help Guides for World DominationWriting Effective Self-Help Guides for World Domination
Writing Effective Self-Help Guides for World Domination
Emma Jane Hogbin Westby
 
Joomla as a mobile App backend - ideas, examples and experiences
Joomla as a mobile App backend - ideas, examples and experiencesJoomla as a mobile App backend - ideas, examples and experiences
Joomla as a mobile App backend - ideas, examples and experiences
Andy_Gaskell
 
Building your first plugin
Building your first pluginBuilding your first plugin
Building your first plugin
Scott DeLuzio
 
Untangling - fall2017 - week5
Untangling - fall2017 - week5Untangling - fall2017 - week5
Untangling - fall2017 - week5
Derek Jacoby
 
Going Global WordPress Multilingual
Going Global WordPress MultilingualGoing Global WordPress Multilingual
Going Global WordPress Multilingual
Rocket WordPress and Internet Marketing Agency
 
Untangling - fall2017 - week6
Untangling - fall2017 - week6Untangling - fall2017 - week6
Untangling - fall2017 - week6
Derek Jacoby
 
What is Drupal? An Introduction to Drupal 8
What is Drupal? An Introduction to Drupal 8What is Drupal? An Introduction to Drupal 8
What is Drupal? An Introduction to Drupal 8
Suzanne Dergacheva
 
Untangling spring week8
Untangling spring week8Untangling spring week8
Untangling spring week8
Derek Jacoby
 
Drupal 8: Most common beginner mistakes
Drupal 8: Most common beginner mistakesDrupal 8: Most common beginner mistakes
Drupal 8: Most common beginner mistakes
Iztok Smolic
 
Plone 5 theming
Plone 5 themingPlone 5 theming
Plone 5 theming
Victor De Alba
 
Introduction to Drupal, Wayne Eaker, Nov 11, 09
Introduction to Drupal, Wayne Eaker, Nov 11, 09 Introduction to Drupal, Wayne Eaker, Nov 11, 09
Introduction to Drupal, Wayne Eaker, Nov 11, 09
Lunch Ann Arbor Marketing
 
Full stack development
Full stack developmentFull stack development
Full stack development
Arnav Gupta
 
Untangling spring week10
Untangling spring week10Untangling spring week10
Untangling spring week10
Derek Jacoby
 
JavaScript : A trending scripting language
JavaScript : A trending scripting languageJavaScript : A trending scripting language
JavaScript : A trending scripting language
AbhayDhupar
 
Top 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal projectTop 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal project
Iztok Smolic
 
Untangling spring week9
Untangling spring week9Untangling spring week9
Untangling spring week9
Derek Jacoby
 
Building a dynamic SPA website with Angular
Building a dynamic SPA website with AngularBuilding a dynamic SPA website with Angular
Building a dynamic SPA website with Angular
Filip Bruun Bech-Larsen
 
Simplifying End-user Drupal 7 Content Administration
Simplifying End-user Drupal 7 Content Administration Simplifying End-user Drupal 7 Content Administration
Simplifying End-user Drupal 7 Content Administration
Aidan Foster
 
Choosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkitChoosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkitHristo Chakarov
 

What's hot (20)

Untangling - fall2017 - week 7
Untangling - fall2017 - week 7Untangling - fall2017 - week 7
Untangling - fall2017 - week 7
 
Writing Effective Self-Help Guides for World Domination
Writing Effective Self-Help Guides for World DominationWriting Effective Self-Help Guides for World Domination
Writing Effective Self-Help Guides for World Domination
 
Joomla as a mobile App backend - ideas, examples and experiences
Joomla as a mobile App backend - ideas, examples and experiencesJoomla as a mobile App backend - ideas, examples and experiences
Joomla as a mobile App backend - ideas, examples and experiences
 
Building your first plugin
Building your first pluginBuilding your first plugin
Building your first plugin
 
Untangling - fall2017 - week5
Untangling - fall2017 - week5Untangling - fall2017 - week5
Untangling - fall2017 - week5
 
Going Global WordPress Multilingual
Going Global WordPress MultilingualGoing Global WordPress Multilingual
Going Global WordPress Multilingual
 
Untangling - fall2017 - week6
Untangling - fall2017 - week6Untangling - fall2017 - week6
Untangling - fall2017 - week6
 
What is Drupal? An Introduction to Drupal 8
What is Drupal? An Introduction to Drupal 8What is Drupal? An Introduction to Drupal 8
What is Drupal? An Introduction to Drupal 8
 
Untangling spring week8
Untangling spring week8Untangling spring week8
Untangling spring week8
 
Drupal 8: Most common beginner mistakes
Drupal 8: Most common beginner mistakesDrupal 8: Most common beginner mistakes
Drupal 8: Most common beginner mistakes
 
Plone 5 theming
Plone 5 themingPlone 5 theming
Plone 5 theming
 
Introduction to Drupal, Wayne Eaker, Nov 11, 09
Introduction to Drupal, Wayne Eaker, Nov 11, 09 Introduction to Drupal, Wayne Eaker, Nov 11, 09
Introduction to Drupal, Wayne Eaker, Nov 11, 09
 
Full stack development
Full stack developmentFull stack development
Full stack development
 
Untangling spring week10
Untangling spring week10Untangling spring week10
Untangling spring week10
 
JavaScript : A trending scripting language
JavaScript : A trending scripting languageJavaScript : A trending scripting language
JavaScript : A trending scripting language
 
Top 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal projectTop 20 mistakes you will make on your 1st Drupal project
Top 20 mistakes you will make on your 1st Drupal project
 
Untangling spring week9
Untangling spring week9Untangling spring week9
Untangling spring week9
 
Building a dynamic SPA website with Angular
Building a dynamic SPA website with AngularBuilding a dynamic SPA website with Angular
Building a dynamic SPA website with Angular
 
Simplifying End-user Drupal 7 Content Administration
Simplifying End-user Drupal 7 Content Administration Simplifying End-user Drupal 7 Content Administration
Simplifying End-user Drupal 7 Content Administration
 
Choosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkitChoosing the best JavaScript framework/library/toolkit
Choosing the best JavaScript framework/library/toolkit
 

Similar to Organizing JavaScript

Professionalizing the Front-end
Professionalizing the Front-endProfessionalizing the Front-end
Professionalizing the Front-end
Jordi Anguela
 
A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...
A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...
A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...
DevGAMM Conference
 
An introduction to Emulsify
An introduction to EmulsifyAn introduction to Emulsify
An introduction to Emulsify
valuebound
 
Introduction to rails
Introduction to railsIntroduction to rails
Introduction to rails
Go Asgard
 
Zero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using DockerZero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using Docker
Tomasz Rękawek
 
Zero downtime deployments for Sling application using Docker
Zero downtime deployments for Sling application using DockerZero downtime deployments for Sling application using Docker
Zero downtime deployments for Sling application using Docker
Robert Munteanu
 
Journeys with Transmogrifier and friends or How not to get stuck in the Plone...
Journeys with Transmogrifier and friends or How not to get stuck in the Plone...Journeys with Transmogrifier and friends or How not to get stuck in the Plone...
Journeys with Transmogrifier and friends or How not to get stuck in the Plone...
Daniel Jowett
 
Plomino plone conf2010
Plomino plone conf2010Plomino plone conf2010
Plomino plone conf2010
ebrehault
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
Dean Hamstead
 
An Introduction to Maven Part 1
An Introduction to Maven Part 1An Introduction to Maven Part 1
An Introduction to Maven Part 1
MD Sayem Ahmed
 
Implementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing CompanyImplementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing Company
Marcos Labad
 
React - The JavaScript Library for User Interfaces
React - The JavaScript Library for User InterfacesReact - The JavaScript Library for User Interfaces
React - The JavaScript Library for User Interfaces
Jumping Bean
 
Everything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is WrongEverything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is Wrong
Tim Boudreau
 
Usable Software Design
Usable Software DesignUsable Software Design
Usable Software Design
Alexandru Bolboaca
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
Abdii Rashid
 
As7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yongAs7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yongjbossug
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
mfrancis
 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master Builder
Philip Norton
 
Bulletproof design systems using storybook
Bulletproof design systems using storybookBulletproof design systems using storybook
Bulletproof design systems using storybook
Chen Feldman
 
JAVA APPLET BASICS
JAVA APPLET BASICSJAVA APPLET BASICS
JAVA APPLET BASICS
Shanid Malayil
 

Similar to Organizing JavaScript (20)

Professionalizing the Front-end
Professionalizing the Front-endProfessionalizing the Front-end
Professionalizing the Front-end
 
A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...
A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...
A few ideas how to integrate Wwise Authoring API (WAAPI) in your project work...
 
An introduction to Emulsify
An introduction to EmulsifyAn introduction to Emulsify
An introduction to Emulsify
 
Introduction to rails
Introduction to railsIntroduction to rails
Introduction to rails
 
Zero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using DockerZero downtime deployments for the Sling-based apps using Docker
Zero downtime deployments for the Sling-based apps using Docker
 
Zero downtime deployments for Sling application using Docker
Zero downtime deployments for Sling application using DockerZero downtime deployments for Sling application using Docker
Zero downtime deployments for Sling application using Docker
 
Journeys with Transmogrifier and friends or How not to get stuck in the Plone...
Journeys with Transmogrifier and friends or How not to get stuck in the Plone...Journeys with Transmogrifier and friends or How not to get stuck in the Plone...
Journeys with Transmogrifier and friends or How not to get stuck in the Plone...
 
Plomino plone conf2010
Plomino plone conf2010Plomino plone conf2010
Plomino plone conf2010
 
Getting big without getting fat, in perl
Getting big without getting fat, in perlGetting big without getting fat, in perl
Getting big without getting fat, in perl
 
An Introduction to Maven Part 1
An Introduction to Maven Part 1An Introduction to Maven Part 1
An Introduction to Maven Part 1
 
Implementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing CompanyImplementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing Company
 
React - The JavaScript Library for User Interfaces
React - The JavaScript Library for User InterfacesReact - The JavaScript Library for User Interfaces
React - The JavaScript Library for User Interfaces
 
Everything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is WrongEverything You Were Taught About Java Is Wrong
Everything You Were Taught About Java Is Wrong
 
Usable Software Design
Usable Software DesignUsable Software Design
Usable Software Design
 
object oriented programming examples
object oriented programming examplesobject oriented programming examples
object oriented programming examples
 
As7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yongAs7 jbug j_boss_modules_yang yong
As7 jbug j_boss_modules_yang yong
 
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
10 clues showing that you are doing OSGi in the wrong manner - Jerome Moliere
 
Becoming A Drupal Master Builder
Becoming A Drupal Master BuilderBecoming A Drupal Master Builder
Becoming A Drupal Master Builder
 
Bulletproof design systems using storybook
Bulletproof design systems using storybookBulletproof design systems using storybook
Bulletproof design systems using storybook
 
JAVA APPLET BASICS
JAVA APPLET BASICSJAVA APPLET BASICS
JAVA APPLET BASICS
 

Recently uploaded

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 

Recently uploaded (20)

Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 

Organizing JavaScript

  • 1. Modules in JavaScript Or How to Break Your Code (Into Little Pieces) A Talk by Michael Cordingley
  • 2. Module Types ● Modules are sometimes misunderstood – ● File Modules – Confusion in naming Each piece of code to its own file They come in different flavors – File – ● ● Logical In an ideal world, the two overlap 1:1 ● Logical Modules – Each piece of code to its own predictable code location
  • 3. The Cost of Structure Three different difficulty levels – Different trade-offs of fixed versus variable costs Complexity vs. Scale Project Complexity ● Project Scale Simple Moderate Complex
  • 4. File Modules ● Break your code out into separate files – ● ● Ideally, one file per idea Files should be small and logically arranged on the filesystem Don't forget about production! – Files need to be concatenated and minified as part of your build process.
  • 5. File Modules – Simple ● ● If a project uses very little JavaScript, throw it it all into a single file for each page. Didn't you just say one idea per file? – ● It's more maintainable to have everything in one place, if that place isn't too cluttered. – ● I lied. We only need organization schemes when we have too much. When starting a new project, START WITH THIS ONE unless you have good reason to do otherwise!
  • 6. File Modules – Moderate ● Break code out into separate files and load them each with a script tag. – ● Don't forget to bundle these into a single file that gets loaded as a giant blob for production Doesn't this get hard to keep up with all of the dependencies? – Only if you have several files – Most projects never reach that scale
  • 7. Transitioning to Moderation ● ● It isn't a clean break Just start pulling your nouns out into separate files as your project acquires them – – ● These are probably reusable across pages anyway Pulling them out also encourages you to write a clean interface If you page script exceeds 200 lines, you probably have lurking nouns, or at least some code that could be DRYed out. – Please don't wait this long!
  • 8. File Modules – Complex ● So you went for the moderate route and now you're drowning in files? – ● Time to level up. Pull in a formalized way to load and compile files – require.js – yepnope.js – etc.
  • 9. Caveat Emptor ● Things like require.js are geared more for single-page apps than for multi-page apps – Most of your projects are probably multi-page apps – You're probably only drowning in JS files if you have a single-page app – require.js becomes painful very quickly if you want to use it on a multi-page app
  • 10. Transitioning to Complexity ● ● ● Update your file module to conform to your module-loader of choice Update every usage of that module to be loaded with the module-loader Don't forget the whole concatenation/minification thing – This is where the pain ramps up – You need to define blobs ● Separate bundlings of code that load together
  • 11. File Modules in the Future ● ECMAScript 6 (Harmony) will bring native modules to the language – Shim: https://github.com/ModuleLoader/es6-module-loader – Despite the shim, this is not yet ready for general consumption ● The spec isn't finished yet
  • 12. Logical Modules ● Where do your objects, functions, and variables all live? – Hint: Not in the global namespace. – I'm not lying this time!
  • 13. Logical Modules – Simple ● Just keep 'em in your page script – ● If you haven't broken it out into its own file anyway, it probably isn't very big or very complicated Pull it out into a logical module at the same time that you'd pull it out into a file module and for the same reasons
  • 14. Logical Modules – Moderate ● OK, so it's out into its own file – Don't make it a global! – Projects get cluttered this way It needs a home that is globally-accessible ● ● ● It may be an object that you reuse across pages It may be repeated functionality – Like enhancing your site navigation
  • 15. Introducing the Application Object ● Make a global – – ● But only one! For now, it's just an object literal Call it “App” or the name of your project: “FooBarFighters” – No, I'm not actually familiar with their music – Yes, the puns are always intentional, even when bad
  • 16. Application Object – Continued ● Attach your modules to this object – – ● e.g. App.Navigation, App.Forms, App.InstantiableObject Submodules go as properties on their parent modules If your module needs initialization, add an “init” or “initialize” method to it. – – ● e.g. App.Navigation.initialize(); This is responsible for calling submodule intializers If you have modules that need initialization, also have an “App.initialize();” method that gets called on DOM ready
  • 17. Application Object – Finish ● This application object can and should be broken out across multiple files. – The “App.initialize()” method saves you from having to worry about the order in which they load The Application object just comes first Don't forget about “this” ● ● – Useful to avoid having to bake the full module name into functions that use other functions – e.g. Inside of “App.Navigation.initialize()” “this” is “App.Navigation”
  • 18. The Catch ● “This is great! Everything is cleanly separated out into its own place, but I need to load a module after the page load and then initialize it.” – ● “Oh yeah, and I don't know if it'll have loaded before the Application starts or not.” – ● OK. Um, K. “And this other piece needs to run only (before|after) the rest is all set up.” – …why are you doing this to me?
  • 19. Logical Modules – Complex ● Introducing the Application object! – ● But this time, it's a real, instantiated object “var App = new Application();” – You could write the definition of “Application” yourself, but it's best not to – We'll get to that
  • 20. The New Application Object ● When a new module gets loaded after the application has started, this will automatically start it. – ● Otherwise, it'll wait until the application starts It also publishes events – – ● So you can run code just before and just after the application starts It even doubles as a free event bus The modules also get events – Same deal as the Application
  • 21. And where do I get this? ● What, you don't want to reinvent the wheel? – ● Fine, here it is: https://github.com/marionettejs/backbone.marionette/blob/m “But, I don't use or want Underscore, Backbone, and the whole rest of Marionette!” – Jeez, you're picky. – https://github.com/mcordingley/Appliance
  • 22. The End Goal ● Reduce complexity – Whenever you introduce a new organizational tool, make sure it reduces project complexity – Use the simplest scheme you can get away with – Make things as easy as possible for anyone who has to maintain your code after you've left it behind
  • 23. Thank You ● This talk can be found in article format at: – http://michaelcordingley.me/articles/when-spaghetti-overflow