#spiffyjs




Spiffy Applications with
JavaScript
July 6th, 2011 @ Webuquerque
Mark Casias / Brian Arnold
JavaScript Basics!
What you need to know before we start
JavaScript Basics


Ultimately, all applications are about information.

What sorts of information can we deal with?

How do we deal with that information?
Variables and Types

A variable is simply a container for information

Information can take on several "types"

JavaScript has a few primitive types

  Strings, Numbers, Booleans, Undefined, Null

Everything else in JavaScript is an Object
Primitive Types

Strings: "Hello Webuquerque!"

Numbers: 42, 3.14, 6.0221415e23

Booleans: true, false

Undefined: undefined

Null: null
Objects

Objects in JavaScript are similar to hashes or
associative arrays or dictionaries in other
languages

Objects are simply collections of key/value pairs,
where the key is a valid identifier or string, and
the value is basically anything you can put into a
variable - All primitives, other objects, etc
Example Object
   var
john
=
{
     name:
"John
Smith",
     age:
32,
     address:
{
       street:
"123
Main
Street",
       city:
"Albuquerque"
     }
   };

   //
Access
via
dot
notation
   john.name
//
=>
"John
Smith"

   //
Access
via
brackets
   john["name"]
//
=>
"John
Smith"
Arrays

Arrays are a special object, similar to array
structures in other languagues

Arrays are not typed, meaning you can have a
mix of types in your array's contents, including
other objects and arrays
Example Arrays
  var
qb
=
[23,
42,
"Hike!"];

  var
tweets
=
[
    {
msg:
'Hi
everybody!'
},
    {
msg:
'Webuquerque
is
awesome!'
}
  ];

  //
Access
via
zero‐indexed
integers
  qb[0];
//
=>
23

  //
Can
combine
accessors
  tweets[0].msg
//
=>
'Hi
everybody!'
JSON
JavaScript Object Notation

  A string representation of a JavaScript object

  May be a single object or an array

  Has a stricter rule syntax than JS Objects

  Several services offer up information in the
  form of JSON, which is very easy for us to
  consume in an application (more on this topic
User Interaction
The Document Object Model (DOM) is a
programmatic representation of your HTML,
turning your tags into elements (DOM nodes)

The DOM is NOT JavaScript! It's an API to
interact with the parsed data structure

Don't be afraid to lean on CSS as well - it's much
more effective to create classes that you toggle
on and off than it is to programmatically style
your nodes
Gathering Information
What can your users provide to you?
Gathering Information

Using HTML/CSS, we can fairly easily create a
simple user interface to make it easy to gather
information from our users

We can then store this information in data
structures that make sense, outside of the DOM,
and update aspects of the DOM as appropriate
to display the information back
Settlers of Catan

Settlers of Catan is a board game that involves
rolling two six-sided die as a game mechanic

Statistics dictate a very standard bell curve for
this type of information, but in small sample
sizes (such as an individual playthrough), certain
roll values seem to occur with disproportionate
frequency
ScoreSettler
ScoreSettler is a small app to gather information
about dice rolls

Key Concepts:

  Simple HTML is used as placeholders for
  information later

  CSS transitions are leveraged where possible

  No library used at all!
         https://github.com/brianarn/ScoreSettler
Twiffy.js
Let’s put this into use.
Consuming Services

Using a technique known as JSON-P, we can
retrieve information from third-party services like
Twitter, Flickr, etc, and then do something with
that information

Using a JavaScript library or toolkit makes this
approach MUCH easier to implement
Creating an application

Twitters API allows us to search, read, and write
tweets from our application.

Key Concepts:

  This application is search only. This way we
  don’t have to mess with permissions and keys.

  We want to start from a blank slate.
The goal
 Create a full application using only Javascript
 starting with this HTML:
            <!DOCTYPE html>
            <html>
               <head>
                  <title></title>
               </head>
               <body>
               </body>
            </html>
Getting things started
            First we need to add the call to jQuery and our
            code
<!DOCTYPE html>
<html>
    <head>
        <title></title>
       <!-- Adding the jQUERY -->
       <script src=”http://code.jquery.com/jquery-1.6.2.min.js”></script>
       <!-- ADDING OUR CODE -->
       <script src=”js/twiffy.js”></script>
    </head>
    <body>
    </body>
</html>
And we’re done with HTML
Back to our application



We are only using the Search API, so no need to:
GO TO

https://dev.twitter.com/apps

This is where you register your spiffy
applications

Also where all the twitter documentation is.
Normally we register

Registering your application allows us more actions

  REST API

  Desktop Applications

  Third Party Integration
API Club



First rule of API Club: There is no API Club
API Club
API’s will change on you.

The better the documentation, the more reliable
the service.

  Twitter, Flickr: good

  Facebook, yFrog: bad

A good change degrades well.

  Twitter: still acknowledges xAuth

  Facebook: less
OK Really back to ours

 First we need to add our search input.

$(document).ready(function(){
  $tweetDiv = $('<div>');
  $input = $('<input type="text" id="whichTweet"' +
              ' size="10" /><input type="button" ' +
              ' id="getTweets" value="Get Tweets"/>');
  $tweetDiv.html($input);
  $('body').append($tweetDiv);
  $("#getTweets").click(getTweets);
});
So now we make the
request!
We wanted the button to do something
$("#getTweets").click(getTweets);



function getTweets() {
  // get the user name
  $tweeter = $("#whichTweet").val();
  // block out the blanks or invalild
  if(!$tweeter) {
    return false;
  }
 /// SNIP
So now we really make
the request!
Continuation of
function getTweets();


  query = {
    q: $tweeter
  }
  // Get em
  $tweets = $.getJSON('http://search.twitter.com/search.json?
callback=?', query, function(tweets){
      console.debug(tweets);
    });
}
console.debug?
happily used in all Modern Browsers.

In this case, prints out the JSON ‘object’ that is
returned.
Why? So you can see that there are results.
console.debug?
happily used in all Modern Browsers.

In this case, prints out the JSON ‘object’ that is
returned.
Why? So you can see that there are results.
What we really want to
do
Display those confounded tweets!



  $tweets = $.getJSON('http://search.twitter.com/search.json?
callback=?', query, function(tweets){
     displayTweets(tweets);
   });
}
Display tweets

OK, it kinda does the same thing:




function displayTweets(tweets) {
  console.debug(tweets.results);
}
OK that was a cop out
Lets get each tweet and display it.

First, make sure there’s a place to put it.

 if (!$('#tweetHolder').length) {
   $('body').append('<div id="tweetHolder">');
 }
 $tweetHolder = $('#tweetHolder');
Now, do we have
tweets?

 if (tweets.results && tweets.results.length) {
    // Do our stuff.
   for(var i in tweets.results){
     $tweet = tweets.results[i];
     console.debug($tweet);
   }
 } else {
   $tweetHolder.html('<p>NO TWEETS FROM ' + tweets.query + '</
p>');
 }
You and your console.debug!
And what each tweet has
So with that:

$('<p/>', {className : 'tweet'})
  .append($('<a/>', {
      href: 'http://twitter.com/' + $from,
      html: '<img src="' + $timage + '"/>'
  }))
  .append($('<span>', {
      className: 'content',
      html: '<a href="http://twitter.com/' + $from +
             '">@' + $from + '</a>: ' + $text
   }))
   .appendTo($tweetHolder);
Adding links

function setMentions(str) {
  return str.replace(/[@]+[A-Za-z0-9-_]+/ig, function(username) {
    return '<a href="http://twitter.com/'+ username.replace('@','')+'">'+username+'</a>';
  });
  console.debug($string);
};

function setHash(str) {
  return str.replace(/[#]+[A-Za-z0-9-_]+/ig, function(tag) {
    return '<a href="http://search.twitter.com/search?q='+tag.replace('#','%23') +
           '">'+tag+'</a>';
  });
};
So with that:


$('<p>', {className : 'tweet'})
  .append($('<a/>', {
      href: 'http://twitter.com/' + $from,
      html: '<img src="' + $timage + '"/>'
  }))
  .append($('<span>', {
      className: 'content',
      html: '<a href="http://twitter.com/' + $from + '">@' + $from + '</a>: ' + $text
   }))
   .appendTo($tweetHolder);
one more thing

I don’t want to redirect to twitter.com.

I want to make each of my links become a
search.
Add a new function

function triggerTweets(linked) {
  target = linked.html().replace('[#@]', '');
  $("#whichTweet").val(target);
  getTweets();
  return false;
}
Link it in your code.


$("#tweetHolder a").click(function(){
  return triggerTweets($(this));
});
This isn’t over.

Many options to still look through.

Many other libraries that do a better job.

Full code available at:
https://github.com/teampoop/Twiffy.js
Advanced Tools
More to life than jQuery
Convenience
As you've seen, using JavaScript libraries can
simplify your code quite a bit

Without using a library of any sorts, doing cross-
browser work is tedious at best, and horribly
painful at worst

jQuery is a fantastic library for DOM, Ajax,
Effects, and Event handling, but there's more to
life than the DOM
It's all about information

Anything beyond simple DOM manipulation is
going to be about information

jQuery does facilitate binding information to
DOM nodes, but it can be difficult to scale well

The number of jQuery tutorials and plugins is
vast and varied, as is the quality, from fantastic
and amazing to painfully broken
Know your Options
There are other code libraries and toolkits

  Dojo

  Prototype

  MooTools

  YUI

  Google Closure

  Sencha (ExtJS)
Dojo
Dojo offers up features that aren't in the browser
by default

  Package management

  Templating

  Cross-browser UI with consistent look and feel

Allows for more modular application
development

Can feel like a higher learning curve, as most
Dojo Demo

A simple application by Rebecca Murphey, to
demonstrate an MVC style approach to
application development

Key concepts:

 Modular, small pieces of code

 Strong separation of concerns in code

        https://github.com/rmurphey/dojo-demo
Summary
What does it all mean?!?
It's all about the info
JavaScript applications are all about information

There are dozens, hundreds of approaches

Use a JS library or toolkit to simplify things, but
be aware of your options

Have fun! Don't be afraid to try things.

Come to Brian's class in October!
Questions?
         http://spkr8.com/t/7912
     @brianarn            @teampoop
brianarn@gmail.com   markie@teampoop.com

Spiffy Applications With JavaScript

  • 1.
    #spiffyjs Spiffy Applications with JavaScript July6th, 2011 @ Webuquerque Mark Casias / Brian Arnold
  • 2.
    JavaScript Basics! What youneed to know before we start
  • 3.
    JavaScript Basics Ultimately, allapplications are about information. What sorts of information can we deal with? How do we deal with that information?
  • 4.
    Variables and Types Avariable is simply a container for information Information can take on several "types" JavaScript has a few primitive types Strings, Numbers, Booleans, Undefined, Null Everything else in JavaScript is an Object
  • 5.
    Primitive Types Strings: "HelloWebuquerque!" Numbers: 42, 3.14, 6.0221415e23 Booleans: true, false Undefined: undefined Null: null
  • 6.
    Objects Objects in JavaScriptare similar to hashes or associative arrays or dictionaries in other languages Objects are simply collections of key/value pairs, where the key is a valid identifier or string, and the value is basically anything you can put into a variable - All primitives, other objects, etc
  • 7.
    Example Object var
john
=
{ name:
"John
Smith", age:
32, address:
{ street:
"123
Main
Street", city:
"Albuquerque" } }; //
Access
via
dot
notation john.name
//
=>
"John
Smith" //
Access
via
brackets john["name"]
//
=>
"John
Smith"
  • 8.
    Arrays Arrays are aspecial object, similar to array structures in other languagues Arrays are not typed, meaning you can have a mix of types in your array's contents, including other objects and arrays
  • 9.
    Example Arrays var
qb
=
[23,
42,
"Hike!"]; var
tweets
=
[ {
msg:
'Hi
everybody!'
}, {
msg:
'Webuquerque
is
awesome!'
} ]; //
Access
via
zero‐indexed
integers qb[0];
//
=>
23 //
Can
combine
accessors tweets[0].msg
//
=>
'Hi
everybody!'
  • 10.
    JSON JavaScript Object Notation A string representation of a JavaScript object May be a single object or an array Has a stricter rule syntax than JS Objects Several services offer up information in the form of JSON, which is very easy for us to consume in an application (more on this topic
  • 11.
    User Interaction The DocumentObject Model (DOM) is a programmatic representation of your HTML, turning your tags into elements (DOM nodes) The DOM is NOT JavaScript! It's an API to interact with the parsed data structure Don't be afraid to lean on CSS as well - it's much more effective to create classes that you toggle on and off than it is to programmatically style your nodes
  • 12.
    Gathering Information What canyour users provide to you?
  • 13.
    Gathering Information Using HTML/CSS,we can fairly easily create a simple user interface to make it easy to gather information from our users We can then store this information in data structures that make sense, outside of the DOM, and update aspects of the DOM as appropriate to display the information back
  • 14.
    Settlers of Catan Settlersof Catan is a board game that involves rolling two six-sided die as a game mechanic Statistics dictate a very standard bell curve for this type of information, but in small sample sizes (such as an individual playthrough), certain roll values seem to occur with disproportionate frequency
  • 15.
    ScoreSettler ScoreSettler is asmall app to gather information about dice rolls Key Concepts: Simple HTML is used as placeholders for information later CSS transitions are leveraged where possible No library used at all! https://github.com/brianarn/ScoreSettler
  • 16.
  • 17.
    Consuming Services Using atechnique known as JSON-P, we can retrieve information from third-party services like Twitter, Flickr, etc, and then do something with that information Using a JavaScript library or toolkit makes this approach MUCH easier to implement
  • 18.
    Creating an application TwittersAPI allows us to search, read, and write tweets from our application. Key Concepts: This application is search only. This way we don’t have to mess with permissions and keys. We want to start from a blank slate.
  • 19.
    The goal Createa full application using only Javascript starting with this HTML: <!DOCTYPE html> <html> <head> <title></title> </head> <body> </body> </html>
  • 20.
    Getting things started First we need to add the call to jQuery and our code <!DOCTYPE html> <html> <head> <title></title> <!-- Adding the jQUERY --> <script src=”http://code.jquery.com/jquery-1.6.2.min.js”></script> <!-- ADDING OUR CODE --> <script src=”js/twiffy.js”></script> </head> <body> </body> </html>
  • 21.
  • 22.
    Back to ourapplication We are only using the Search API, so no need to:
  • 23.
    GO TO https://dev.twitter.com/apps This iswhere you register your spiffy applications Also where all the twitter documentation is.
  • 24.
    Normally we register Registeringyour application allows us more actions REST API Desktop Applications Third Party Integration
  • 25.
    API Club First ruleof API Club: There is no API Club
  • 26.
    API Club API’s willchange on you. The better the documentation, the more reliable the service. Twitter, Flickr: good Facebook, yFrog: bad A good change degrades well. Twitter: still acknowledges xAuth Facebook: less
  • 27.
    OK Really backto ours First we need to add our search input. $(document).ready(function(){ $tweetDiv = $('<div>'); $input = $('<input type="text" id="whichTweet"' + ' size="10" /><input type="button" ' + ' id="getTweets" value="Get Tweets"/>'); $tweetDiv.html($input); $('body').append($tweetDiv); $("#getTweets").click(getTweets); });
  • 28.
    So now wemake the request! We wanted the button to do something $("#getTweets").click(getTweets); function getTweets() { // get the user name $tweeter = $("#whichTweet").val(); // block out the blanks or invalild if(!$tweeter) { return false; } /// SNIP
  • 29.
    So now wereally make the request! Continuation of function getTweets(); query = { q: $tweeter } // Get em $tweets = $.getJSON('http://search.twitter.com/search.json? callback=?', query, function(tweets){ console.debug(tweets); }); }
  • 30.
    console.debug? happily used inall Modern Browsers. In this case, prints out the JSON ‘object’ that is returned. Why? So you can see that there are results.
  • 31.
    console.debug? happily used inall Modern Browsers. In this case, prints out the JSON ‘object’ that is returned. Why? So you can see that there are results.
  • 32.
    What we reallywant to do Display those confounded tweets! $tweets = $.getJSON('http://search.twitter.com/search.json? callback=?', query, function(tweets){ displayTweets(tweets); }); }
  • 33.
    Display tweets OK, itkinda does the same thing: function displayTweets(tweets) { console.debug(tweets.results); }
  • 34.
    OK that wasa cop out Lets get each tweet and display it. First, make sure there’s a place to put it. if (!$('#tweetHolder').length) { $('body').append('<div id="tweetHolder">'); } $tweetHolder = $('#tweetHolder');
  • 35.
    Now, do wehave tweets? if (tweets.results && tweets.results.length) { // Do our stuff. for(var i in tweets.results){ $tweet = tweets.results[i]; console.debug($tweet); } } else { $tweetHolder.html('<p>NO TWEETS FROM ' + tweets.query + '</ p>'); }
  • 36.
    You and yourconsole.debug!
  • 37.
    And what eachtweet has
  • 38.
    So with that: $('<p/>',{className : 'tweet'}) .append($('<a/>', { href: 'http://twitter.com/' + $from, html: '<img src="' + $timage + '"/>' })) .append($('<span>', { className: 'content', html: '<a href="http://twitter.com/' + $from + '">@' + $from + '</a>: ' + $text })) .appendTo($tweetHolder);
  • 39.
    Adding links function setMentions(str){ return str.replace(/[@]+[A-Za-z0-9-_]+/ig, function(username) { return '<a href="http://twitter.com/'+ username.replace('@','')+'">'+username+'</a>'; }); console.debug($string); }; function setHash(str) { return str.replace(/[#]+[A-Za-z0-9-_]+/ig, function(tag) { return '<a href="http://search.twitter.com/search?q='+tag.replace('#','%23') + '">'+tag+'</a>'; }); };
  • 40.
    So with that: $('<p>',{className : 'tweet'}) .append($('<a/>', { href: 'http://twitter.com/' + $from, html: '<img src="' + $timage + '"/>' })) .append($('<span>', { className: 'content', html: '<a href="http://twitter.com/' + $from + '">@' + $from + '</a>: ' + $text })) .appendTo($tweetHolder);
  • 41.
    one more thing Idon’t want to redirect to twitter.com. I want to make each of my links become a search.
  • 42.
    Add a newfunction function triggerTweets(linked) { target = linked.html().replace('[#@]', ''); $("#whichTweet").val(target); getTweets(); return false; }
  • 43.
    Link it inyour code. $("#tweetHolder a").click(function(){ return triggerTweets($(this)); });
  • 44.
    This isn’t over. Manyoptions to still look through. Many other libraries that do a better job. Full code available at: https://github.com/teampoop/Twiffy.js
  • 45.
    Advanced Tools More tolife than jQuery
  • 46.
    Convenience As you've seen,using JavaScript libraries can simplify your code quite a bit Without using a library of any sorts, doing cross- browser work is tedious at best, and horribly painful at worst jQuery is a fantastic library for DOM, Ajax, Effects, and Event handling, but there's more to life than the DOM
  • 47.
    It's all aboutinformation Anything beyond simple DOM manipulation is going to be about information jQuery does facilitate binding information to DOM nodes, but it can be difficult to scale well The number of jQuery tutorials and plugins is vast and varied, as is the quality, from fantastic and amazing to painfully broken
  • 48.
    Know your Options Thereare other code libraries and toolkits Dojo Prototype MooTools YUI Google Closure Sencha (ExtJS)
  • 49.
    Dojo Dojo offers upfeatures that aren't in the browser by default Package management Templating Cross-browser UI with consistent look and feel Allows for more modular application development Can feel like a higher learning curve, as most
  • 50.
    Dojo Demo A simpleapplication by Rebecca Murphey, to demonstrate an MVC style approach to application development Key concepts: Modular, small pieces of code Strong separation of concerns in code https://github.com/rmurphey/dojo-demo
  • 51.
  • 52.
    It's all aboutthe info JavaScript applications are all about information There are dozens, hundreds of approaches Use a JS library or toolkit to simplify things, but be aware of your options Have fun! Don't be afraid to try things. Come to Brian's class in October!
  • 53.
    Questions? http://spkr8.com/t/7912 @brianarn @teampoop brianarn@gmail.com markie@teampoop.com

Editor's Notes