SlideShare a Scribd company logo
1 of 32
JAVASCRIPT &
1ST CLASS CITIZENRY

Fast, modular code with RequireJS &
node.js
                              talks@goneopen.com
Size and complexity
As JavaScript applications grow in size and
complexity we need a real tool to handle
dependencies and keep our code modular.
RequireJS give you an easy way to define
dependencies on your module and it'll make
sure it‟s loaded before your code runs. It also
has a nice build system which can be used to
compress and obfuscate your code using a
closure compiler.
  Adapted from: http://www.meetup.com/jQuery-Boston/events/16191792/
Agenda
• Global Pollution
• Dependencies &
  Modularisation
• Building and Testing
• Optimisation
Global Pollution
In Javascript, global functions are not a
good strategy. They pollute. So, too do well
known namespaces – but we‟ll live with
that. Modules provide a way forward
against these problems.
Badness 1: Global functions
<body>
      <button onclick="addMovie()">add
Movie</button>
      <script type="text/javascript”>
           function addMovie() {
            $.observable( movies ).insert (
this.name);
                }
           </script>
</body>
Badness 2: Well-known namespaces
<html>
<head>
          <script src=http://code.jquery.com/jquery.js …
          <script src="jsrender.js" type="text/javascript"></script>
</head>
<body>
          <div id="movieList"><b>Our Movies</b><br /></div>

           <script type="text/javascript”>
                               $.templates({ movieTemplate: "#movieList” })
                     $.template.moveTemplate.render( )
           </script>
</body>
</html>
Template Pattern

(function($) {
    // nothing outside here can call this function
    function sumWithInterest( el, interset){
       return $(el).val() * interest;
    }
    $.extend($.fn , sumWithInterest) // except …
}(jQuery));
RequireJs (module) pattern

define([“jquery”], function($) {
     function sumWithInterest( el, interest){
       return $(el) .val() * interest;
     }
    return sumWithInterest// object or function
});
Dependencies & Modularisation
Let‟s take that all a little bit more slowly.
Each module ecapsulates
Create                     Consume

define(“main”,             require(“main”)
  function(){
      //all code in here
          // is scoped
  }
)
Access in is via a return only
Create            Consume

define(“main”,    require(“main”).init()
  function(){
      return {
      init:
function(){…}
      }
    }
)
Dependencies are explicit

define(“main”, [„log‟, „jquery‟],
  function( log, $ ){
       log.debug( $(„body‟).text() )

    }
)
Module loading can be ordered
define(“main”, [„log‟, „order!jquery‟, „order!jsrende
r‟],
    function( log, $ ){
       $.template(„body‟).render()
       log.debug( $(„body‟).text() )
    }
)
Building & Testing
Build command line
•   Rake
•   Gradle
•   Psake
•   Msbuild
•   Ant
•   Bat
•   sh
Test-first via jasmine
Units
• Views
• Events

Acceptance
• Full loading
Test html
           Code template <li>
                              <i>{{:type}}</i> (<abbr
                           class="date”{{:ordered}}</abbr>)
                           </li>

Test
describe("Html views", function() {
 var data = { type: "small", ordered: "1 min ago" }

  it("has a line item", function() {
   _requires(["text!coffee/views/_item.html", 'jsrender'],
         function( text ){
            $( "#test" ).html( $.templates( text ).render( data ) );
            expect($("li", "#test" ).size()).toEqual(1);
      });
  }
Test Events
it("should register add order handler”, function() {
     _requires([“coffee/loader”]));
    spyOn(_, 'order').andCallThrough()
    _.orderHandler( $('#test'), function(){ return {} )

  $('#test').click()

   expect(_.order).toHaveBeenCalled()
 });
Test that it actually works!

    it("should be able to add new order", function()
{
       _requires(["coffee/main"]));
       val = $('li', ‟#orders').size();
       $('button.order', ‟#orders').click()

expect($('li', ‟#orders').size()).toEqual(val++);
 });
Build and get runtime errors
$ rake build
node lib/r.js -o app.build.js

Tracing dependencies for: coffee/main

Error: Error evaluating module "undefined" at
location
"/Users/todd/Documents/src/coffee/build/scripts/
coffee/main.js":
Unexpected token: punc (,) (line: 4, col: 16, pos:
152)
Throw away the debugger


 no break points or step through

   … no really, I‟m serious
Optimisation
We still need to package code ready for
serving. Why wait until run?
Script-tag vomit
In development, it’s good   Production, it’s not
Pretty clean
Create bundles & linted
Script and CSS compressed
Ready for deployment
Gotchas!
• File paths between development and
    production
•   CSS url paths
•   Text (html, json) loading without server
•   Creating a localhost server for text
•   Hassle for smaller projects
Follow-up areas
•   Different AMD implementations
•   Plugins (page load, internationalisation)
•   Lazy and dynamic loading
•   Wrapping non-AMD code
•   Coffeescript
•   Data-main loading
•   Build runners and CI integration
Finally, what does this mean?
• We can unit test web-based application at the
  GUI layer
• We CAN reduce the number of
  expensive, system tests (eg selenium)
• Modularity and testing are likely to allow
  smaller pieces of work and potentially
  increased flow
• All this (coupled with REST) means interesting
  times!
Useful refs (and referred to
materials)


• http://www.angrycoding.com/2011/09/managing-dependencies-with-
    requirejs.html
•   http://patrickmcelhaney.com/AMD-Talk/#microjs
•   http://projects.haykranen.nl/amsterdamjs
•   http://www.slideshare.net/JulienZee/parisjs-10-requirejs-9111799
•   http://www.slideshare.net/tim_doherty/requirejs-8858167
•   http://www.slideshare.net/timoxley/testable-client-sidemvcappsinjavascript
•   http://www.slideshare.net/sioked/requirejs
Good luck
                               Todd Brackley

                               goneopen.com
                               twitter: toddbNZ


  code: github.com/toddb/javascript-amd

More Related Content

What's hot

AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersCaldera Labs
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPressCaldera Labs
 
Unobtrusive JavaScript
Unobtrusive JavaScriptUnobtrusive JavaScript
Unobtrusive JavaScriptVitaly Baum
 
Обзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScriptОбзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScriptCOMAQA.BY
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBApaichon Punopas
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDartLoc Nguyen
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
ReactJs presentation
ReactJs presentationReactJs presentation
ReactJs presentationnishasowdri
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterpriseDave Artz
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSSimon Guest
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJSWei Ru
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 

What's hot (20)

AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
Unobtrusive JavaScript
Unobtrusive JavaScriptUnobtrusive JavaScript
Unobtrusive JavaScript
 
Обзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScriptОбзор автоматизации тестирования на JavaScript
Обзор автоматизации тестирования на JavaScript
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
AngularJs
AngularJsAngularJs
AngularJs
 
Dart and AngularDart
Dart and AngularDartDart and AngularDart
Dart and AngularDart
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
The AngularJS way
The AngularJS wayThe AngularJS way
The AngularJS way
 
ReactJs presentation
ReactJs presentationReactJs presentation
ReactJs presentation
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
jQuery in the [Aol.] Enterprise
jQuery in the [Aol.] EnterprisejQuery in the [Aol.] Enterprise
jQuery in the [Aol.] Enterprise
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
React
React React
React
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 

Similar to Javascript first-class citizenery

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETBen Hall
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english versionSabino Labarile
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebJames Rakich
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 

Similar to Javascript first-class citizenery (20)

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Testing ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
e-suap - client technologies- english version
e-suap - client technologies- english versione-suap - client technologies- english version
e-suap - client technologies- english version
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the Web
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 

Recently uploaded

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Javascript first-class citizenery

  • 1. JAVASCRIPT & 1ST CLASS CITIZENRY Fast, modular code with RequireJS & node.js talks@goneopen.com
  • 2. Size and complexity As JavaScript applications grow in size and complexity we need a real tool to handle dependencies and keep our code modular. RequireJS give you an easy way to define dependencies on your module and it'll make sure it‟s loaded before your code runs. It also has a nice build system which can be used to compress and obfuscate your code using a closure compiler. Adapted from: http://www.meetup.com/jQuery-Boston/events/16191792/
  • 3. Agenda • Global Pollution • Dependencies & Modularisation • Building and Testing • Optimisation
  • 4. Global Pollution In Javascript, global functions are not a good strategy. They pollute. So, too do well known namespaces – but we‟ll live with that. Modules provide a way forward against these problems.
  • 5. Badness 1: Global functions <body> <button onclick="addMovie()">add Movie</button> <script type="text/javascript”> function addMovie() { $.observable( movies ).insert ( this.name); } </script> </body>
  • 6. Badness 2: Well-known namespaces <html> <head> <script src=http://code.jquery.com/jquery.js … <script src="jsrender.js" type="text/javascript"></script> </head> <body> <div id="movieList"><b>Our Movies</b><br /></div> <script type="text/javascript”> $.templates({ movieTemplate: "#movieList” }) $.template.moveTemplate.render( ) </script> </body> </html>
  • 7. Template Pattern (function($) { // nothing outside here can call this function function sumWithInterest( el, interset){ return $(el).val() * interest; } $.extend($.fn , sumWithInterest) // except … }(jQuery));
  • 8. RequireJs (module) pattern define([“jquery”], function($) { function sumWithInterest( el, interest){ return $(el) .val() * interest; } return sumWithInterest// object or function });
  • 9. Dependencies & Modularisation Let‟s take that all a little bit more slowly.
  • 10. Each module ecapsulates Create Consume define(“main”, require(“main”) function(){ //all code in here // is scoped } )
  • 11. Access in is via a return only Create Consume define(“main”, require(“main”).init() function(){ return { init: function(){…} } } )
  • 12. Dependencies are explicit define(“main”, [„log‟, „jquery‟], function( log, $ ){ log.debug( $(„body‟).text() ) } )
  • 13. Module loading can be ordered define(“main”, [„log‟, „order!jquery‟, „order!jsrende r‟], function( log, $ ){ $.template(„body‟).render() log.debug( $(„body‟).text() ) } )
  • 15. Build command line • Rake • Gradle • Psake • Msbuild • Ant • Bat • sh
  • 16. Test-first via jasmine Units • Views • Events Acceptance • Full loading
  • 17. Test html Code template <li> <i>{{:type}}</i> (<abbr class="date”{{:ordered}}</abbr>) </li> Test describe("Html views", function() { var data = { type: "small", ordered: "1 min ago" } it("has a line item", function() { _requires(["text!coffee/views/_item.html", 'jsrender'], function( text ){ $( "#test" ).html( $.templates( text ).render( data ) ); expect($("li", "#test" ).size()).toEqual(1); }); }
  • 18. Test Events it("should register add order handler”, function() { _requires([“coffee/loader”])); spyOn(_, 'order').andCallThrough() _.orderHandler( $('#test'), function(){ return {} ) $('#test').click() expect(_.order).toHaveBeenCalled() });
  • 19. Test that it actually works! it("should be able to add new order", function() { _requires(["coffee/main"])); val = $('li', ‟#orders').size(); $('button.order', ‟#orders').click() expect($('li', ‟#orders').size()).toEqual(val++); });
  • 20. Build and get runtime errors $ rake build node lib/r.js -o app.build.js Tracing dependencies for: coffee/main Error: Error evaluating module "undefined" at location "/Users/todd/Documents/src/coffee/build/scripts/ coffee/main.js": Unexpected token: punc (,) (line: 4, col: 16, pos: 152)
  • 21. Throw away the debugger no break points or step through … no really, I‟m serious
  • 22. Optimisation We still need to package code ready for serving. Why wait until run?
  • 23. Script-tag vomit In development, it’s good Production, it’s not
  • 26. Script and CSS compressed
  • 28. Gotchas! • File paths between development and production • CSS url paths • Text (html, json) loading without server • Creating a localhost server for text • Hassle for smaller projects
  • 29. Follow-up areas • Different AMD implementations • Plugins (page load, internationalisation) • Lazy and dynamic loading • Wrapping non-AMD code • Coffeescript • Data-main loading • Build runners and CI integration
  • 30. Finally, what does this mean? • We can unit test web-based application at the GUI layer • We CAN reduce the number of expensive, system tests (eg selenium) • Modularity and testing are likely to allow smaller pieces of work and potentially increased flow • All this (coupled with REST) means interesting times!
  • 31. Useful refs (and referred to materials) • http://www.angrycoding.com/2011/09/managing-dependencies-with- requirejs.html • http://patrickmcelhaney.com/AMD-Talk/#microjs • http://projects.haykranen.nl/amsterdamjs • http://www.slideshare.net/JulienZee/parisjs-10-requirejs-9111799 • http://www.slideshare.net/tim_doherty/requirejs-8858167 • http://www.slideshare.net/timoxley/testable-client-sidemvcappsinjavascript • http://www.slideshare.net/sioked/requirejs
  • 32. Good luck Todd Brackley goneopen.com twitter: toddbNZ code: github.com/toddb/javascript-amd