KEMBAR78
HTML5 for the Silverlight Guy | PDF
HTML5 for the
   Silverlight Guy
  An introduction to “Serious”
development on the Web Platform
               David Padbury
          http://davidpadbury.com
              @davidpadbury
So, this whole Silverlight vs HTML5 has
       been a little controversial...
“Microsoft execs said tonight ... allow them to create Windows 8
            applications in HTML and/or JavaScript.
 Sinofsky and others didn’t mention Silverlight or XNA at all.”
 http://www.zdnet.com/blog/microsoft/windows-8-more-than-just-windows-phone-on-your-pc/9592?tag=mantle_skin;content
http://forums.silverlight.net/forums/p/230502/562113.aspx#562081
“...they want us to write freaking javascript. Really!?”

    “HTML5??? Microsoft isn't eating their own dogfood, they're eating their own vomit.”

    “It may just be a very cool thing if they are brewing a way to utilize html5 + javascript
**without us having to mess with javascript** (exactly what ASP.NET does on the client side)”


     “At this point html5/js is a horrible development platform... I have not seen a single
                              project developed purely in html/js.”

              “we get Html and JavaScarriness in place of the beauty we know”

    “Seriously, who decided that we should start basing all of our computing around the
                              most abysmally slow language!?”

                   “Contrary to popular belief, HTML 5 is not ready yet.”

      “there is no way you would write a trading application in HTML5 and javascript”

    Javascript may be the WORST language ever used to write "applications".  It's a joke.
“You can’t write serious applications in
        HTML and JavaScript.”
There’s lots of cool HTML5 demos out there
But how do I build a rich front end application?



    That’s what I’m going to (try) helping you understand today.
But ïŹrst.

             Silverlight is not dead.

Evaluate HTML5 the same way you would anything else.

      It’s good at some things, it sucks at others.
Although this is the web,
forget your server side web programming experience.

                 ASP.NET, Rails, Grails, PHP



             Well, not entirely but you’ll see where I’m going.
                        I’m trying to be dramatic.
Writing complex front-end in HTML+JavaScript
has more in common with WPF/SL than ASP.NET

           For you guys, this is a good thing.
Let’s talk business.
Application is built from modules
Modules are decoupled from each other
         Code is easy to test
Runs on Desktop, RIA, and   (windows 7)   Phone
Today’s Talk

      JavaScript
 JavaScript Modules
Module Organization
  Views as Modules                     Decoupling and Testing
                                        Event Aggregator/PubSub
                                        Unit Testing View Modules
           CSS
   CSS Compilers
Platform Consistency
                                        HTML5 Everywhere
We’re going to talk about the                   Plugins
   boring bits of HTML5                         Devices
“JavaScript doesn’t suck.
          You’re just doing it wrong.”
                - Douglas Crockford
                (father of JSON and JSLint, author of The Good Parts)




            The tone’s a little harsh, but he has a point.
Despite looking similar to C#, JavaScript is a very different language.
JavaScript is a very simple language
   If you can learn C#, you can cope with JavaScript.
There are three things you have to learn to
     be a great JavaScript developer.



           First Class Functions

                Prototypes

                 Context
First Class Functions
function createCounter() {
    var count = 0;

     return function() {
         return count++;
     };
}

var counter1 = createCounter(),
    counter2 = createCounter();

console.log(   counter1()   );   //   0
console.log(   counter1()   );   //   1
console.log(   counter2()   );   //   0
console.log(   counter1()   );   //   2
Context
               Or, which this is this?

var david = {
    name: 'David',
    sayHi: function() {
        console.log("Hi, I'm " + this.name);
    }
};

david.sayHi(); // Hi, I'm David
// obj.fn() is eqv to obj.fn.call(obj)

david.sayHi.call({name:'Colleen'});
// Hi, I'm Colleen
Prototypes


function Person(name) {
    this.name = name;
}

Person.prototype.sayHi = function() {
    console.log("Hi, I'm " + this.name);
};

var david = new Person('David'),
    colleen = new Person('Colleen');

david.sayHi(); // Hi, I'm David
colleen.sayHi(); // Hi, I'm Colleen

console.log( david.sayHi === colleen.sayHi ); // true
Some older bits aren’t great...
strict mode keeps us on the Good Parts


          Start a ïŹle with ‘use   strict’;

      'use strict';

      alert( "I'm in strict mode." );



     Or start a function with ‘use   strict’;

     (function() {
         'use strict';

         alert("I'm in strict mode!");
     })();
(function() {
    globalVariable = 'OOPS!';
})();

console.log(globalVariable);
// OOPS!
(function() {
          'use strict';
          globalVariable = 'OOPS!';
      })();

      console.log(globalVariable);


ReferenceError: globalVariable is not defined
var person;

(function() {
    person = {
        name: 'David',
        name: 'Colleen'
    };
})();

console.log(person.name);
// Colleen
var person;

       (function() {
           'use strict';
           person = {
               name: 'David',
               name: 'Colleen'
           };
       })();

       console.log(person.name);

 SyntaxError: Duplicate data property in
object literal not allowed in strict mode
(function() {
    console.log( 012 + 2 );
})();
(function() {
    console.log( 012 + 2 );   // 12?!
})();
(function() {
   'use strict';
    console.log( 012 + 2 );
})();

SyntaxError: Octal literals are not
      allowed in strict mode.
In some ways, too simple.
C# has using



Visual Basic has Imports



     JavaScript has?
C# has using



Visual Basic has Imports



     JavaScript has?
        Nothing.
<!DOCTYPE HTML>
<html>
    <body>
        <script>
            // Application goes here...
        </script>
    </body>
</html>
$(document).ready(function() {
    function addSymbol(symbol) {
        var row = $('<tr>').append($('<td>').text(symbol));
        $('.watches').children().append(row);
    }
    $('.screen-switcher a').click(function() {
        var screen = $(this).attr('data-screen-id');
        $('.screens .screen').slideUp('fast', function() {
            $('.screens .screen[data-screen=' + screen + ']').slideDown();
        });
    });
    $('.add-symbol').parent('form').submit(function(e) {
        e.preventDefault();
        var symbol = $('.add-symbol').val();
        addSymbol(symbol);
        $.ajax('/data/symbol' + symbol, {
            completed: function(xhr, data) {
                $('<div class="price">')
                    .text(data.price)
                    .click(function() {
                        $('.price .tooltip')
                            .show('fast', function() {
                                 $(this).text(price);
                            })
                    });
            }
        });
    });
    $('.sidebar .history').flot({
        data: $.ajax('/stock/history', {
            data: [1,23,4,5,6],
            date: new Date().getTime()
        });
Everything is global by default

// lib1.js
function something() {
    console.log('foo');
}

// lib2.js
function something() {
    console.log('bar');
}

<script src="lib1.js"></script>
<script src="lib2.js"></script>
<script>
    something(); // bar
</script>
The patterns and tools and practices that will
form the foundation of Modern JavaScript are
     going to have to come from outside
    implementations of the language itself
                                - Rebecca Murphey
Using simple JavaScript constructs we can emulate many
          traditional organization techniques

     (function(lab49) {

         function privateAdder(n1, n2) {
             return n1 + n2;
         }

         lab49.add = function(n1, n2) {
             return privateAdder(n1, n2);
         };

     })(window.lab49 = window.lab49 || {});


     lab49.add(2, 3);


            Known as the Module Pattern
             http://blog.davidpadbury.com/2011/08/21/javascript-modules/
Using simple JavaScript constructs we can emulate many
          traditional organization techniques

     (function(lab49) {

         function privateAdder(n1, n2) {
             return n1 + n2;
         }

         lab49.add = function(n1, n2) {
             return privateAdder(n1, n2);
         };

     })(window.lab49 = window.lab49 || {});


     lab49.add(2, 3);


            Known as the Module Pattern
             http://blog.davidpadbury.com/2011/08/21/javascript-modules/
Using simple JavaScript constructs we can emulate many
          traditional organization techniques

     (function(lab49) {

         function privateAdder(n1, n2) {
             return n1 + n2;
         }

         lab49.add = function(n1, n2) {
             return privateAdder(n1, n2);
         };

     })(window.lab49 = window.lab49 || {});


     lab49.add(2, 3);


            Known as the Module Pattern
             http://blog.davidpadbury.com/2011/08/21/javascript-modules/
Using simple JavaScript constructs we can emulate many
          traditional organization techniques

     (function(lab49) {

         function privateAdder(n1, n2) {
             return n1 + n2;
         }

         lab49.add = function(n1, n2) {
             return privateAdder(n1, n2);
         };

     })(window.lab49 = window.lab49 || {});


     lab49.add(2, 3);


            Known as the Module Pattern
             http://blog.davidpadbury.com/2011/08/21/javascript-modules/
Modules have evolved into standard patterns with
     tooling to help loading and packaging.

       Asynchronous Module DeïŹnition
         (Commonly known as AMD)




             https://github.com/amdjs/amdjs-api/wiki/AMD
define for creating a module deïŹnition.




require to ask for a module instance.
define('calculator', function() {
    return {
        add: function(n1, n2) {
             return n1 + n2;
        }
    };                  Callback so modules can be loaded asynchronously
});

require(['calculator'], function(calculator) {
    console.log( calculator.add(1, 2) ); // 3
});
define('math/adder', function() {
    return {
        add: function(n1, n2) {
             return n1 + n2;
        }            Specify modules this module depends on
    }
});

define('math/calculator', ['./adder'], function(adder) {
    return {
        add: function(n1, n2) {
             return adder.add(n1, n2);
        }
    };                              Loader passes instances of them
});
Loaders can assume module names from ïŹles
// math/adder.js
define(function() {
    return {
        add: function(n1, n2) {
             return n1 + n2;
        }
    }
});

// math/calculator.js
define(['./adder'], function(adder) {
    return {
        add: function(n1, n2) {
             return adder.add(n1, n2);
        }
    };
});
AMD appears to be winning in how to large JavaScript code bases



          There are a number of AMD module loaders
                        RequireJS, curl.js




             Popular libraries are supporting AMD
                    Dojo, jQuery (as of 1.7)
Demo
Basic RequireJS
You can extend how modules are loaded using plugins




                    text!
                    i18n!
                    order!
// views/personView.html
<div>My name is: <span class="name"></span></div>
// views/personView.html
<div>My name is: <span class="name"></span></div>

// views/personView.js
define(['text!./personView.html'], function(tmpl) {
    function PersonView(options) {
        var el = $(options.el),
                                           Ask for content with the text
            name = options.name;            plugin and we get a String

          el.html(tmpl).find('.name').text(name);
      }
      return PersonView;
});
// views/personView.html
<div>My name is: <span class="name"></span></div>

// views/personView.js
define(['text!./personView.html'], function(tmpl) {
    function PersonView(options) {
        var el = $(options.el),
                                           Ask for content with the text
            name = options.name;            plugin and we get a String

          el.html(tmpl).find('.name').text(name);
      }
      return PersonView;
});

// index.html
<div id="person"></div>
<script>
    require(['views/personView'], function(PersonView) {
         var personView = new PersonView({
             el: $('#person'), name: 'David'
         });
    });
</script>
This allows us to organize our
                   applications the way we’re used to




               C#                          JavaScript
(Yep, I know you would’ve guessed...)
Demo
“Controls” with RequireJS
require(['pubsub'], function(PubSub) {
    var bus = new PubSub();

      bus.sub('say', function(msg) {
          console.log('Subscriber 1 says: ' + msg);
      });

      bus.sub('say', function(msg) {
          console.log('Subscriber 2 says: ' + msg);
      });

      bus.pub('say', 'Nope!');
      // Subscriber 1 says: Nope!
      // Subscriber 2 says: Nope!
});
“Dictionary” to hold topic to
define('pubsub', function() {                         list of subscriptions
    function PubSub() {
        this.subs = {};
    }
                                                         Create topic list if none exists
      PubSub.prototype = {
          sub: function(topic, fn) {
              var topicSubs = (this.subs[topic] = this.subs[topic] || []);
              topicSubs.push(fn);
          },
          pub: function(topic, data) {
              var topicSubs = this.subs[topic] || [];
              topicSubs.forEach(function(fn) {
                  fn(data);
              });
          }
      };                        Call each subscriber for topic
      return PubSub;
});

                 (This is is a horribly crap implementation - DON’T EVER USE IT!)
Demo
pubsub
The ease of Unit Testing is one of the
  biggest plus points for JavaScript


        There’s a lot less ïŹghting the compiler.
Which is handy, as they’re useful as there is no compiler.
There is a large number of unit testing libraries and frameworks
                        QUnit (of jQuery fame)
                          Jasmine (BDD’ish)
describe('Calculator', function() {
    var calculator;

      beforeEach(function() {
          calculator = require('calculator');
      });

      it('should add two numbers correctly', function() {
          expect(calculator.add(2, 3)).toEqual(5);
      });
});
Demo
Unit Testing jQuery and mocks
CSS is wonderfully simple.



           selector {
               property: value;
           }




But sometimes it feels a little too simple.
Take it up a level - CSS Compilers


                            SASS
       WebWorkbench (VS), SassAndCoffee (ASP.NET), Ruby


                             LESS
WebWorkbench (VS), dotless (ASP.NET), Java, Ruby, Node, JavaScript


                            Stylus
                              Node
Repetition in CSS sucks



.content-navigation {
  border-color: #3bbfce;
}

.border {
  border-color: #3bbfce;
}
SASS gives us variables


$blue: #3bbfce;
                                   .content-navigation {
.content-navigation {                border-color: #3bbfce;
  border-color: $blue;             }
}
                                   .border {
.border {                            border-color: #3bbfce;
  border-color: $blue;             }
}
                                             CSS
         SASS
Having to repeat selector paths sucks




  header { background-color: blue; }

  header a { font-weight: normal; }

  header a:hover { font-weight: bold; }
SASS gives us nesting
 header {
     background-color: blue;

     a {
           font-weight: normal;
           &:hover {                    SASS
               font-weight: bold;
           }
     }
 }




header { background-color: blue; }

header a { font-weight: normal; }       CSS
header a:hover { font-weight: bold; }
Having to repeat vendor preïŹxes sucks




        #container {
            -ms-box-flex: 1;
            -o-box-flex: 1;
            -webkit-box-flex: 1;
            -moz-box-flex: 1;
            box-flex: 1;
        }
SASS gives us mixins


@mixin box-flex($flex) {
    -ms-box-flex: $flex;
    -o-box-flex: $flex;           #container {
    -webkit-box-flex: $flex;          -ms-box-flex: 1;
    -ms-box-flex: $flex;              -o-box-flex: 1;
    box-flex: $flex;                  -webkit-box-flex: 1;
}                                     -moz-box-flex: 1;
                                      box-flex: 1;
#container {                      }
    @include box-flex(1);
}                                           CSS

           SASS
Platform Consistency


Or, everyone else’s browser sucks.
Writing an app for a single
       browser is easy.




Writing a single app for multiple
    browsers can be hard.
Just ask it

function hasCssProp(prop) {
    var el = document.createElement('div'),
        style = el.style;

    return typeof style[prop] == 'string';
}

// In IE9, Chrome, Firefox, etc...
hasCssProp('borderRadius'); // true

// In IE6, IE7, IE8, etc...
hasCssProp('borderRadius'); // false
14



8
Demo
Modernizr + SASS + CSS3 Hawtness + CSS2 Not-so-hawtness
The elephant in the room...




“But my company is all IE6...”
border-radius: 8px;
box-shadow: #666 0px 2px 3px;
background: linear-gradient(#eeff99, #66ee33);
behavior: url(/PIE.htc);




                   http://css3pie.com/
You can fake a lot.

But honestly, it sucks.




   Accept reality.
Chrome Frame - a plugin with beneïŹts

                            System Admin Compatible
                                        Roll out with MSI

                                Control with Group Policy Settings

                                    User Installable
                                   Just include a script in page

                                  Non-admin installs supported


                                           Keep IE
                          Sites have to explicitly opt-in to Chrome Frame

                             Sites depending on IE6/7 stay in IE6/7
        http://www.google.com/chromeframe
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">




    Applications have to explicitly opt-in so your legacy applications won’t be affected
Demo
HTML5 Everywhere
Running the same application - http://html5trader.com
Internet Explorer 6                          iPhone




Running the same application - http://html5trader.com
“This HTML5 stuff would be ïŹne,
if only there was decent tooling...”
Visual Studio 11 is looking much better...




 http://blogs.msdn.com/b/webdevtools/archive/2011/09/15/new-javascript-editing-features-
              for-web-development-in-visual-studio-11-developer-preview.aspx
We use Intellisense to
‘Explore’ and ‘Discover’

        http://www.ïŹ‚ickr.com/photos/gemmabou/4622213880/
With modern browsers we can easily and
 quickly explore our code at runtime
Smaller Surfaces
// Getter
$('#test').css('backgroundColor');

// Setter
$('#test').css('backgroundColor', 'red');

// Bigger setter
$('#test').css({
    backgroundColor: 'red'
});
Static analysis for JavaScript
function add(a, b, c) {
  return a + b;
}
function add(a, b, c) {
  return a + b;
}
var person = {
    name: 'David',
    company: 'Lab49',
};
var person = {
    name: 'David',
    company: 'Lab49',
};
function createPerson(name) {
    return
    {
        name: name
    };
}
function createPerson(name) {
    return
    {
        name: name
    };
}
There’s tons of other tools....

       Automation Testing
           Validators
         Performance
          Debuggers
            ProïŹlers
           Designers
On many other platforms...

           .NET
            Java
           Ruby
          Python
           Node
It is not Silverlight vs HTML5
They’re both valid options with different pros and cons
You guys are experts in building front-end applications.


      Although the code looks a little different...

          The patterns, techniques and good
               practices are the same.
Be ConïŹdent
 Be Fearless
 (and be sensible)
Hang on,

           You went an entire talk to a Silverlight
         audience and didn’t once mention MVVM?



Yep - although you can reuse a lot of knowledge, don’t try to do everything exactly the same.
            I encourage you to start with the simplest thing and build from there.
You didn’t cover ...!?
                                           Acceptance Testing
   CoffeeScript
                           Underscore
Templates                        Server Tools           IOC
             jQuery                  JavaScriptMVC

 HTML5 Boiler Plate         KnockOut               Flow Control

   Project Silk                                   BDD
                       Backbone
ECMAScript 6                              ASP.NET Integration

               jQuery UI
                               Promises         GoldïŹsh
  Script Loaders
Dec 6th
               RequireJS 1.0

Callbacks, Promises and Coroutines (on my!)
The NY HTML5 Application Developers Group


                   Dec 6th
                  RequireJS 1.0

 Callbacks, Promises and Coroutines (on my!)




      http://www.meetup.com/html5-app-developers
New York .NET Meetup


http://www.meetup.com/NY-Dotnet
http://www.lab49.com
// Thanks for listening!

return;

HTML5 for the Silverlight Guy

  • 1.
    HTML5 for the Silverlight Guy An introduction to “Serious” development on the Web Platform David Padbury http://davidpadbury.com @davidpadbury
  • 2.
    So, this wholeSilverlight vs HTML5 has been a little controversial...
  • 3.
    “Microsoft execs saidtonight ... allow them to create Windows 8 applications in HTML and/or JavaScript. Sinofsky and others didn’t mention Silverlight or XNA at all.” http://www.zdnet.com/blog/microsoft/windows-8-more-than-just-windows-phone-on-your-pc/9592?tag=mantle_skin;content
  • 5.
  • 6.
    “...they want usto write freaking javascript. Really!?” “HTML5??? Microsoft isn't eating their own dogfood, they're eating their own vomit.” “It may just be a very cool thing if they are brewing a way to utilize html5 + javascript **without us having to mess with javascript** (exactly what ASP.NET does on the client side)” “At this point html5/js is a horrible development platform... I have not seen a single project developed purely in html/js.” “we get Html and JavaScarriness in place of the beauty we know” “Seriously, who decided that we should start basing all of our computing around the most abysmally slow language!?” “Contrary to popular belief, HTML 5 is not ready yet.” “there is no way you would write a trading application in HTML5 and javascript” Javascript may be the WORST language ever used to write "applications".  It's a joke.
  • 8.
    “You can’t writeserious applications in HTML and JavaScript.”
  • 9.
    There’s lots ofcool HTML5 demos out there
  • 10.
    But how doI build a rich front end application? That’s what I’m going to (try) helping you understand today.
  • 11.
    But ïŹrst. Silverlight is not dead. Evaluate HTML5 the same way you would anything else. It’s good at some things, it sucks at others.
  • 12.
    Although this isthe web, forget your server side web programming experience. ASP.NET, Rails, Grails, PHP Well, not entirely but you’ll see where I’m going. I’m trying to be dramatic.
  • 13.
    Writing complex front-endin HTML+JavaScript has more in common with WPF/SL than ASP.NET For you guys, this is a good thing.
  • 14.
  • 16.
    Application is builtfrom modules Modules are decoupled from each other Code is easy to test Runs on Desktop, RIA, and (windows 7) Phone
  • 17.
    Today’s Talk JavaScript JavaScript Modules Module Organization Views as Modules Decoupling and Testing Event Aggregator/PubSub Unit Testing View Modules CSS CSS Compilers Platform Consistency HTML5 Everywhere We’re going to talk about the Plugins boring bits of HTML5 Devices
  • 18.
    “JavaScript doesn’t suck. You’re just doing it wrong.” - Douglas Crockford (father of JSON and JSLint, author of The Good Parts) The tone’s a little harsh, but he has a point. Despite looking similar to C#, JavaScript is a very different language.
  • 19.
    JavaScript is avery simple language If you can learn C#, you can cope with JavaScript.
  • 20.
    There are threethings you have to learn to be a great JavaScript developer. First Class Functions Prototypes Context
  • 21.
    First Class Functions functioncreateCounter() { var count = 0; return function() { return count++; }; } var counter1 = createCounter(), counter2 = createCounter(); console.log( counter1() ); // 0 console.log( counter1() ); // 1 console.log( counter2() ); // 0 console.log( counter1() ); // 2
  • 22.
    Context Or, which this is this? var david = { name: 'David', sayHi: function() { console.log("Hi, I'm " + this.name); } }; david.sayHi(); // Hi, I'm David // obj.fn() is eqv to obj.fn.call(obj) david.sayHi.call({name:'Colleen'}); // Hi, I'm Colleen
  • 23.
    Prototypes function Person(name) { this.name = name; } Person.prototype.sayHi = function() { console.log("Hi, I'm " + this.name); }; var david = new Person('David'), colleen = new Person('Colleen'); david.sayHi(); // Hi, I'm David colleen.sayHi(); // Hi, I'm Colleen console.log( david.sayHi === colleen.sayHi ); // true
  • 24.
    Some older bitsaren’t great...
  • 25.
    strict mode keepsus on the Good Parts Start a ïŹle with ‘use strict’; 'use strict'; alert( "I'm in strict mode." ); Or start a function with ‘use strict’; (function() { 'use strict'; alert("I'm in strict mode!"); })();
  • 26.
    (function() { globalVariable = 'OOPS!'; })(); console.log(globalVariable); // OOPS!
  • 27.
    (function() { 'use strict'; globalVariable = 'OOPS!'; })(); console.log(globalVariable); ReferenceError: globalVariable is not defined
  • 28.
    var person; (function() { person = { name: 'David', name: 'Colleen' }; })(); console.log(person.name); // Colleen
  • 29.
    var person; (function() { 'use strict'; person = { name: 'David', name: 'Colleen' }; })(); console.log(person.name); SyntaxError: Duplicate data property in object literal not allowed in strict mode
  • 30.
    (function() { console.log( 012 + 2 ); })();
  • 31.
    (function() { console.log( 012 + 2 ); // 12?! })();
  • 32.
    (function() { 'use strict'; console.log( 012 + 2 ); })(); SyntaxError: Octal literals are not allowed in strict mode.
  • 33.
    In some ways,too simple.
  • 34.
    C# has using VisualBasic has Imports JavaScript has?
  • 35.
    C# has using VisualBasic has Imports JavaScript has? Nothing.
  • 36.
    <!DOCTYPE HTML> <html> <body> <script> // Application goes here... </script> </body> </html>
  • 37.
    $(document).ready(function() { function addSymbol(symbol) { var row = $('<tr>').append($('<td>').text(symbol)); $('.watches').children().append(row); } $('.screen-switcher a').click(function() { var screen = $(this).attr('data-screen-id'); $('.screens .screen').slideUp('fast', function() { $('.screens .screen[data-screen=' + screen + ']').slideDown(); }); }); $('.add-symbol').parent('form').submit(function(e) { e.preventDefault(); var symbol = $('.add-symbol').val(); addSymbol(symbol); $.ajax('/data/symbol' + symbol, { completed: function(xhr, data) { $('<div class="price">') .text(data.price) .click(function() { $('.price .tooltip') .show('fast', function() { $(this).text(price); }) }); } }); }); $('.sidebar .history').flot({ data: $.ajax('/stock/history', { data: [1,23,4,5,6], date: new Date().getTime() });
  • 38.
    Everything is globalby default // lib1.js function something() { console.log('foo'); } // lib2.js function something() { console.log('bar'); } <script src="lib1.js"></script> <script src="lib2.js"></script> <script> something(); // bar </script>
  • 39.
    The patterns andtools and practices that will form the foundation of Modern JavaScript are going to have to come from outside implementations of the language itself - Rebecca Murphey
  • 40.
    Using simple JavaScriptconstructs we can emulate many traditional organization techniques (function(lab49) { function privateAdder(n1, n2) { return n1 + n2; } lab49.add = function(n1, n2) { return privateAdder(n1, n2); }; })(window.lab49 = window.lab49 || {}); lab49.add(2, 3); Known as the Module Pattern http://blog.davidpadbury.com/2011/08/21/javascript-modules/
  • 41.
    Using simple JavaScriptconstructs we can emulate many traditional organization techniques (function(lab49) { function privateAdder(n1, n2) { return n1 + n2; } lab49.add = function(n1, n2) { return privateAdder(n1, n2); }; })(window.lab49 = window.lab49 || {}); lab49.add(2, 3); Known as the Module Pattern http://blog.davidpadbury.com/2011/08/21/javascript-modules/
  • 42.
    Using simple JavaScriptconstructs we can emulate many traditional organization techniques (function(lab49) { function privateAdder(n1, n2) { return n1 + n2; } lab49.add = function(n1, n2) { return privateAdder(n1, n2); }; })(window.lab49 = window.lab49 || {}); lab49.add(2, 3); Known as the Module Pattern http://blog.davidpadbury.com/2011/08/21/javascript-modules/
  • 43.
    Using simple JavaScriptconstructs we can emulate many traditional organization techniques (function(lab49) { function privateAdder(n1, n2) { return n1 + n2; } lab49.add = function(n1, n2) { return privateAdder(n1, n2); }; })(window.lab49 = window.lab49 || {}); lab49.add(2, 3); Known as the Module Pattern http://blog.davidpadbury.com/2011/08/21/javascript-modules/
  • 44.
    Modules have evolvedinto standard patterns with tooling to help loading and packaging. Asynchronous Module DeïŹnition (Commonly known as AMD) https://github.com/amdjs/amdjs-api/wiki/AMD
  • 45.
    define for creatinga module deïŹnition. require to ask for a module instance.
  • 46.
    define('calculator', function() { return { add: function(n1, n2) { return n1 + n2; } }; Callback so modules can be loaded asynchronously }); require(['calculator'], function(calculator) { console.log( calculator.add(1, 2) ); // 3 });
  • 47.
    define('math/adder', function() { return { add: function(n1, n2) { return n1 + n2; } Specify modules this module depends on } }); define('math/calculator', ['./adder'], function(adder) { return { add: function(n1, n2) { return adder.add(n1, n2); } }; Loader passes instances of them });
  • 48.
    Loaders can assumemodule names from ïŹles // math/adder.js define(function() { return { add: function(n1, n2) { return n1 + n2; } } }); // math/calculator.js define(['./adder'], function(adder) { return { add: function(n1, n2) { return adder.add(n1, n2); } }; });
  • 49.
    AMD appears tobe winning in how to large JavaScript code bases There are a number of AMD module loaders RequireJS, curl.js Popular libraries are supporting AMD Dojo, jQuery (as of 1.7)
  • 50.
  • 51.
    You can extendhow modules are loaded using plugins text! i18n! order!
  • 52.
    // views/personView.html <div>My nameis: <span class="name"></span></div>
  • 53.
    // views/personView.html <div>My nameis: <span class="name"></span></div> // views/personView.js define(['text!./personView.html'], function(tmpl) { function PersonView(options) { var el = $(options.el), Ask for content with the text name = options.name; plugin and we get a String el.html(tmpl).find('.name').text(name); } return PersonView; });
  • 54.
    // views/personView.html <div>My nameis: <span class="name"></span></div> // views/personView.js define(['text!./personView.html'], function(tmpl) { function PersonView(options) { var el = $(options.el), Ask for content with the text name = options.name; plugin and we get a String el.html(tmpl).find('.name').text(name); } return PersonView; }); // index.html <div id="person"></div> <script> require(['views/personView'], function(PersonView) { var personView = new PersonView({ el: $('#person'), name: 'David' }); }); </script>
  • 55.
    This allows usto organize our applications the way we’re used to C# JavaScript (Yep, I know you would’ve guessed...)
  • 56.
  • 58.
    require(['pubsub'], function(PubSub) { var bus = new PubSub(); bus.sub('say', function(msg) { console.log('Subscriber 1 says: ' + msg); }); bus.sub('say', function(msg) { console.log('Subscriber 2 says: ' + msg); }); bus.pub('say', 'Nope!'); // Subscriber 1 says: Nope! // Subscriber 2 says: Nope! });
  • 59.
    “Dictionary” to holdtopic to define('pubsub', function() { list of subscriptions function PubSub() { this.subs = {}; } Create topic list if none exists PubSub.prototype = { sub: function(topic, fn) { var topicSubs = (this.subs[topic] = this.subs[topic] || []); topicSubs.push(fn); }, pub: function(topic, data) { var topicSubs = this.subs[topic] || []; topicSubs.forEach(function(fn) { fn(data); }); } }; Call each subscriber for topic return PubSub; }); (This is is a horribly crap implementation - DON’T EVER USE IT!)
  • 60.
  • 61.
    The ease ofUnit Testing is one of the biggest plus points for JavaScript There’s a lot less ïŹghting the compiler. Which is handy, as they’re useful as there is no compiler.
  • 62.
    There is alarge number of unit testing libraries and frameworks QUnit (of jQuery fame) Jasmine (BDD’ish)
  • 63.
    describe('Calculator', function() { var calculator; beforeEach(function() { calculator = require('calculator'); }); it('should add two numbers correctly', function() { expect(calculator.add(2, 3)).toEqual(5); }); });
  • 65.
  • 66.
    CSS is wonderfullysimple. selector { property: value; } But sometimes it feels a little too simple.
  • 67.
    Take it upa level - CSS Compilers SASS WebWorkbench (VS), SassAndCoffee (ASP.NET), Ruby LESS WebWorkbench (VS), dotless (ASP.NET), Java, Ruby, Node, JavaScript Stylus Node
  • 68.
    Repetition in CSSsucks .content-navigation { border-color: #3bbfce; } .border { border-color: #3bbfce; }
  • 69.
    SASS gives usvariables $blue: #3bbfce; .content-navigation { .content-navigation { border-color: #3bbfce; border-color: $blue; } } .border { .border { border-color: #3bbfce; border-color: $blue; } } CSS SASS
  • 70.
    Having to repeatselector paths sucks header { background-color: blue; } header a { font-weight: normal; } header a:hover { font-weight: bold; }
  • 71.
    SASS gives usnesting header { background-color: blue; a { font-weight: normal; &:hover { SASS font-weight: bold; } } } header { background-color: blue; } header a { font-weight: normal; } CSS header a:hover { font-weight: bold; }
  • 72.
    Having to repeatvendor preïŹxes sucks #container { -ms-box-flex: 1; -o-box-flex: 1; -webkit-box-flex: 1; -moz-box-flex: 1; box-flex: 1; }
  • 73.
    SASS gives usmixins @mixin box-flex($flex) { -ms-box-flex: $flex; -o-box-flex: $flex; #container { -webkit-box-flex: $flex; -ms-box-flex: 1; -ms-box-flex: $flex; -o-box-flex: 1; box-flex: $flex; -webkit-box-flex: 1; } -moz-box-flex: 1; box-flex: 1; #container { } @include box-flex(1); } CSS SASS
  • 74.
    Platform Consistency Or, everyoneelse’s browser sucks.
  • 75.
    Writing an appfor a single browser is easy. Writing a single app for multiple browsers can be hard.
  • 76.
    Just ask it functionhasCssProp(prop) { var el = document.createElement('div'), style = el.style; return typeof style[prop] == 'string'; } // In IE9, Chrome, Firefox, etc... hasCssProp('borderRadius'); // true // In IE6, IE7, IE8, etc... hasCssProp('borderRadius'); // false
  • 78.
  • 79.
    Demo Modernizr + SASS+ CSS3 Hawtness + CSS2 Not-so-hawtness
  • 80.
    The elephant inthe room... “But my company is all IE6...”
  • 81.
    border-radius: 8px; box-shadow: #6660px 2px 3px; background: linear-gradient(#eeff99, #66ee33); behavior: url(/PIE.htc); http://css3pie.com/
  • 83.
    You can fakea lot. But honestly, it sucks. Accept reality.
  • 84.
    Chrome Frame -a plugin with beneïŹts System Admin Compatible Roll out with MSI Control with Group Policy Settings User Installable Just include a script in page Non-admin installs supported Keep IE Sites have to explicitly opt-in to Chrome Frame Sites depending on IE6/7 stay in IE6/7 http://www.google.com/chromeframe
  • 85.
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> Applications have to explicitly opt-in so your legacy applications won’t be affected
  • 86.
  • 87.
    Running the sameapplication - http://html5trader.com
  • 88.
    Internet Explorer 6 iPhone Running the same application - http://html5trader.com
  • 89.
    “This HTML5 stuffwould be ïŹne, if only there was decent tooling...”
  • 91.
    Visual Studio 11is looking much better... http://blogs.msdn.com/b/webdevtools/archive/2011/09/15/new-javascript-editing-features- for-web-development-in-visual-studio-11-developer-preview.aspx
  • 94.
    We use Intellisenseto ‘Explore’ and ‘Discover’ http://www.ïŹ‚ickr.com/photos/gemmabou/4622213880/
  • 95.
    With modern browserswe can easily and quickly explore our code at runtime
  • 96.
  • 97.
    // Getter $('#test').css('backgroundColor'); // Setter $('#test').css('backgroundColor','red'); // Bigger setter $('#test').css({ backgroundColor: 'red' });
  • 98.
  • 99.
    function add(a, b,c) { return a + b; }
  • 100.
    function add(a, b,c) { return a + b; }
  • 101.
    var person ={ name: 'David', company: 'Lab49', };
  • 102.
    var person ={ name: 'David', company: 'Lab49', };
  • 103.
    function createPerson(name) { return { name: name }; }
  • 104.
    function createPerson(name) { return { name: name }; }
  • 105.
    There’s tons ofother tools.... Automation Testing Validators Performance Debuggers ProïŹlers Designers
  • 106.
    On many otherplatforms... .NET Java Ruby Python Node
  • 107.
    It is notSilverlight vs HTML5 They’re both valid options with different pros and cons
  • 108.
    You guys areexperts in building front-end applications. Although the code looks a little different... The patterns, techniques and good practices are the same.
  • 109.
    Be ConïŹdent BeFearless (and be sensible)
  • 110.
    Hang on, You went an entire talk to a Silverlight audience and didn’t once mention MVVM? Yep - although you can reuse a lot of knowledge, don’t try to do everything exactly the same. I encourage you to start with the simplest thing and build from there.
  • 111.
    You didn’t cover...!? Acceptance Testing CoffeeScript Underscore Templates Server Tools IOC jQuery JavaScriptMVC HTML5 Boiler Plate KnockOut Flow Control Project Silk BDD Backbone ECMAScript 6 ASP.NET Integration jQuery UI Promises GoldïŹsh Script Loaders
  • 112.
    Dec 6th RequireJS 1.0 Callbacks, Promises and Coroutines (on my!)
  • 113.
    The NY HTML5Application Developers Group Dec 6th RequireJS 1.0 Callbacks, Promises and Coroutines (on my!) http://www.meetup.com/html5-app-developers
  • 114.
    New York .NETMeetup http://www.meetup.com/NY-Dotnet
  • 115.
  • 116.
    // Thanks forlistening! return;

Editor's Notes