Spiffy Applications With JavaScript

1,553 views

Published on

You understand the basics of jQuery to handle some events and maybe do some animation, but there's a lot more that you could be doing.

Local JavaScript experts Mark Casias and Brian Arnold will walk you through a few examples of using jQuery and JavaScript to tackle a couple of common issues, as well as how to create a simple application that utilizes information from other services.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,553
On SlideShare
0
From Embeds
0
Number of Embeds
84
Actions
Shares
0
Downloads
9
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • May refer to information as 'data' throughout the presentation - effectively synonymous for our purposes\n
  • Undefined means the variable does not have a value yet, null means it is expressly set to a known empty value of sorts\n
  • Strings can be single or double, doesn't matter\nAll numbers are IEEE 754 doubles, no integer types\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Spiffy Applications With JavaScript

    1. 1. #spiffyjsSpiffy Applications withJavaScriptJuly 6th, 2011 @ WebuquerqueMark Casias / Brian Arnold
    2. 2. JavaScript Basics!What you need to know before we start
    3. 3. JavaScript BasicsUltimately, all applications are about information.What sorts of information can we deal with?How do we deal with that information?
    4. 4. Variables and TypesA variable is simply a container for informationInformation can take on several "types"JavaScript has a few primitive types Strings, Numbers, Booleans, Undefined, NullEverything else in JavaScript is an Object
    5. 5. Primitive TypesStrings: "Hello Webuquerque!"Numbers: 42, 3.14, 6.0221415e23Booleans: true, falseUndefined: undefinedNull: null
    6. 6. ObjectsObjects in JavaScript are similar to hashes orassociative arrays or dictionaries in otherlanguagesObjects are simply collections of key/value pairs,where the key is a valid identifier or string, andthe value is basically anything you can put into avariable - All primitives, other objects, etc
    7. 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. 8. ArraysArrays are a special object, similar to arraystructures in other languaguesArrays are not typed, meaning you can have amix of types in your arrays contents, includingother objects and arrays
    9. 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. 10. JSONJavaScript 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. 11. User InteractionThe Document Object Model (DOM) is aprogrammatic representation of your HTML,turning your tags into elements (DOM nodes)The DOM is NOT JavaScript! Its an API tointeract with the parsed data structureDont be afraid to lean on CSS as well - its muchmore effective to create classes that you toggleon and off than it is to programmatically styleyour nodes
    12. 12. Gathering InformationWhat can your users provide to you?
    13. 13. Gathering InformationUsing HTML/CSS, we can fairly easily create asimple user interface to make it easy to gatherinformation from our usersWe can then store this information in datastructures that make sense, outside of the DOM,and update aspects of the DOM as appropriateto display the information back
    14. 14. Settlers of CatanSettlers of Catan is a board game that involvesrolling two six-sided die as a game mechanicStatistics dictate a very standard bell curve forthis type of information, but in small samplesizes (such as an individual playthrough), certainroll values seem to occur with disproportionatefrequency
    15. 15. ScoreSettlerScoreSettler is a small app to gather informationabout dice rollsKey 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. 16. Twiffy.jsLet’s put this into use.
    17. 17. Consuming ServicesUsing a technique known as JSON-P, we canretrieve information from third-party services likeTwitter, Flickr, etc, and then do something withthat informationUsing a JavaScript library or toolkit makes thisapproach MUCH easier to implement
    18. 18. Creating an applicationTwitters API allows us to search, read, and writetweets 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. 19. The goal Create a full application using only Javascript starting with this HTML: <!DOCTYPE html> <html> <head> <title></title> </head> <body> </body> </html>
    20. 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. 21. And we’re done with HTML
    22. 22. Back to our applicationWe are only using the Search API, so no need to:
    23. 23. GO TOhttps://dev.twitter.com/appsThis is where you register your spiffyapplicationsAlso where all the twitter documentation is.
    24. 24. Normally we registerRegistering your application allows us more actions REST API Desktop Applications Third Party Integration
    25. 25. API ClubFirst rule of API Club: There is no API Club
    26. 26. API ClubAPI’s will change on you.The better the documentation, the more reliablethe service. Twitter, Flickr: good Facebook, yFrog: badA good change degrades well. Twitter: still acknowledges xAuth Facebook: less
    27. 27. 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);});
    28. 28. So now we make therequest!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. 29. So now we really makethe request!Continuation offunction getTweets(); query = { q: $tweeter } // Get em $tweets = $.getJSON(http://search.twitter.com/search.json?callback=?, query, function(tweets){ console.debug(tweets); });}
    30. 30. console.debug?happily used in all Modern Browsers.In this case, prints out the JSON ‘object’ that isreturned.Why? So you can see that there are results.
    31. 31. console.debug?happily used in all Modern Browsers.In this case, prints out the JSON ‘object’ that isreturned.Why? So you can see that there are results.
    32. 32. What we really want todoDisplay those confounded tweets! $tweets = $.getJSON(http://search.twitter.com/search.json?callback=?, query, function(tweets){ displayTweets(tweets); });}
    33. 33. Display tweetsOK, it kinda does the same thing:function displayTweets(tweets) { console.debug(tweets.results);}
    34. 34. OK that was a cop outLets 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. 35. Now, do we havetweets? 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. 36. You and your console.debug!
    37. 37. And what each tweet has
    38. 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. 39. Adding linksfunction 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. 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. 41. one more thingI don’t want to redirect to twitter.com.I want to make each of my links become asearch.
    42. 42. Add a new functionfunction triggerTweets(linked) { target = linked.html().replace([#@], ); $("#whichTweet").val(target); getTweets(); return false;}
    43. 43. Link it in your code.$("#tweetHolder a").click(function(){ return triggerTweets($(this));});
    44. 44. 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
    45. 45. Advanced ToolsMore to life than jQuery
    46. 46. ConvenienceAs youve seen, using JavaScript libraries cansimplify your code quite a bitWithout using a library of any sorts, doing cross-browser work is tedious at best, and horriblypainful at worstjQuery is a fantastic library for DOM, Ajax,Effects, and Event handling, but theres more tolife than the DOM
    47. 47. Its all about informationAnything beyond simple DOM manipulation isgoing to be about informationjQuery does facilitate binding information toDOM nodes, but it can be difficult to scale wellThe number of jQuery tutorials and plugins isvast and varied, as is the quality, from fantasticand amazing to painfully broken
    48. 48. Know your OptionsThere are other code libraries and toolkits Dojo Prototype MooTools YUI Google Closure Sencha (ExtJS)
    49. 49. DojoDojo offers up features that arent in the browserby default Package management Templating Cross-browser UI with consistent look and feelAllows for more modular applicationdevelopmentCan feel like a higher learning curve, as most
    50. 50. Dojo DemoA simple application by Rebecca Murphey, todemonstrate an MVC style approach toapplication developmentKey concepts: Modular, small pieces of code Strong separation of concerns in code https://github.com/rmurphey/dojo-demo
    51. 51. SummaryWhat does it all mean?!?
    52. 52. Its all about the infoJavaScript applications are all about informationThere are dozens, hundreds of approachesUse a JS library or toolkit to simplify things, butbe aware of your optionsHave fun! Dont be afraid to try things.Come to Brians class in October!
    53. 53. Questions? http://spkr8.com/t/7912 @brianarn @teampoopbrianarn@gmail.com markie@teampoop.com

    ×