SlideShare una empresa de Scribd logo
1 de 53
#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

Más contenido relacionado

La actualidad más candente

Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™Nicola Iarocci
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsIgnacio Martín
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery PresentationRod Johnson
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009Remy Sharp
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQueryGunjan Kumar
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTim Cull
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQueryIban Martinez
 
Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)Donny Wals
 
Java script browser objects 1
Java script browser objects 1Java script browser objects 1
Java script browser objects 1H K
 

La actualidad más candente (20)

Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™
 
jQuery
jQueryjQuery
jQuery
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
Learn css3
Learn css3Learn css3
Learn css3
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Pushing the Web: Interesting things to Know
Pushing the Web: Interesting things to KnowPushing the Web: Interesting things to Know
Pushing the Web: Interesting things to Know
 
HTML5 Essentials
HTML5 EssentialsHTML5 Essentials
HTML5 Essentials
 
jQuery
jQueryjQuery
jQuery
 
Tips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applicationsTips and tricks for building api heavy ruby on rails applications
Tips and tricks for building api heavy ruby on rails applications
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Jquery tutorial
Jquery tutorialJquery tutorial
Jquery tutorial
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
 
Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)Improving apps with iOS 10 notifications (do iOS 2016)
Improving apps with iOS 10 notifications (do iOS 2016)
 
Java script browser objects 1
Java script browser objects 1Java script browser objects 1
Java script browser objects 1
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 

Similar a Spiffy Applications With JavaScript

Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + djangoNina Zakharenko
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsNeil Crookes
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchKaty Slemon
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Ted Kulp
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsEugene Andruszczenko
 
Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Thinkful
 
Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)
Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)
Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)Cogapp
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4Heather Rock
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial IntroPamela Fox
 
API Technical Writing
API Technical WritingAPI Technical Writing
API Technical WritingSarah Maddox
 
Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02
Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02
Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02careersblog
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and PythonPiXeL16
 

Similar a Spiffy Applications With JavaScript (20)

Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
How to build twitter bot using golang from scratch
How to build twitter bot using golang from scratchHow to build twitter bot using golang from scratch
How to build twitter bot using golang from scratch
 
Api
ApiApi
Api
 
Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101Geek Moot '09 -- Smarty 101
Geek Moot '09 -- Smarty 101
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
 
Client-Server
Client-ServerClient-Server
Client-Server
 
Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18Build an App with JavaScript and jQuery - LA - July 18
Build an App with JavaScript and jQuery - LA - July 18
 
Learning Svelte
Learning SvelteLearning Svelte
Learning Svelte
 
Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)
Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)
Test-driven Development with Drupal and Codeception (DrupalCamp Brighton)
 
GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4GDI Seattle - Intro to JavaScript Class 4
GDI Seattle - Intro to JavaScript Class 4
 
J query intro_29thsep_alok
J query intro_29thsep_alokJ query intro_29thsep_alok
J query intro_29thsep_alok
 
OpenSocial Intro
OpenSocial IntroOpenSocial Intro
OpenSocial Intro
 
68837.ppt
68837.ppt68837.ppt
68837.ppt
 
API Technical Writing
API Technical WritingAPI Technical Writing
API Technical Writing
 
Site optimization
Site optimizationSite optimization
Site optimization
 
Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02
Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02
Jqueryforbeginnersjqueryconference2009 090914063709 Phpapp02
 
2018 03 20_biological_databases_part3
2018 03 20_biological_databases_part32018 03 20_biological_databases_part3
2018 03 20_biological_databases_part3
 
REST with Eve and Python
REST with Eve and PythonREST with Eve and Python
REST with Eve and Python
 
Playing With The Web
Playing With The WebPlaying With The Web
Playing With The Web
 

Más de Mark Casias

Backing yourself into an Accessible Corner
Backing yourself into an Accessible CornerBacking yourself into an Accessible Corner
Backing yourself into an Accessible CornerMark Casias
 
Backend accessible
Backend accessibleBackend accessible
Backend accessibleMark Casias
 
Constantly Contributing Pretty Patches FLCD
Constantly Contributing Pretty Patches FLCDConstantly Contributing Pretty Patches FLCD
Constantly Contributing Pretty Patches FLCDMark Casias
 
ABQ Drupal Users Group Presentation 2014/07/10
ABQ Drupal Users Group Presentation 2014/07/10ABQ Drupal Users Group Presentation 2014/07/10
ABQ Drupal Users Group Presentation 2014/07/10Mark Casias
 
Something drupal this way comes
Something drupal this way comesSomething drupal this way comes
Something drupal this way comesMark Casias
 
Idiots guide to jquery
Idiots guide to jqueryIdiots guide to jquery
Idiots guide to jqueryMark Casias
 
Libraries Frameworks And Cms
Libraries Frameworks And CmsLibraries Frameworks And Cms
Libraries Frameworks And CmsMark Casias
 

Más de Mark Casias (8)

Backing yourself into an Accessible Corner
Backing yourself into an Accessible CornerBacking yourself into an Accessible Corner
Backing yourself into an Accessible Corner
 
Backend accessible
Backend accessibleBackend accessible
Backend accessible
 
Constantly Contributing Pretty Patches FLCD
Constantly Contributing Pretty Patches FLCDConstantly Contributing Pretty Patches FLCD
Constantly Contributing Pretty Patches FLCD
 
ABQ Drupal Users Group Presentation 2014/07/10
ABQ Drupal Users Group Presentation 2014/07/10ABQ Drupal Users Group Presentation 2014/07/10
ABQ Drupal Users Group Presentation 2014/07/10
 
Something drupal this way comes
Something drupal this way comesSomething drupal this way comes
Something drupal this way comes
 
Using PHP
Using PHPUsing PHP
Using PHP
 
Idiots guide to jquery
Idiots guide to jqueryIdiots guide to jquery
Idiots guide to jquery
 
Libraries Frameworks And Cms
Libraries Frameworks And CmsLibraries Frameworks And Cms
Libraries Frameworks And Cms
 

Último

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
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
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Último (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
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
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

Spiffy Applications With JavaScript

  • 1. #spiffyjs Spiffy Applications with JavaScript July 6th, 2011 @ Webuquerque Mark Casias / Brian Arnold
  • 2. JavaScript Basics! What you need to know before we start
  • 3. JavaScript Basics Ultimately, all applications are about information. What sorts of information can we deal with? How do we deal with that information?
  • 4. 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
  • 5. Primitive Types Strings: "Hello Webuquerque!" Numbers: 42, 3.14, 6.0221415e23 Booleans: true, false Undefined: undefined Null: null
  • 6. 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
  • 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 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
  • 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 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
  • 12. Gathering Information What can your 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 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
  • 15. 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
  • 17. 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
  • 18. 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.
  • 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. 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. And we’re done with HTML
  • 22. Back to our application We are only using the Search API, so no need to:
  • 23. GO TO https://dev.twitter.com/apps This is where you register your spiffy applications Also where all the twitter documentation is.
  • 24. Normally we register Registering your application allows us more actions REST API Desktop Applications Third Party Integration
  • 25. API Club First rule of API Club: There is no API Club
  • 26. 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
  • 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. 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
  • 29. 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); }); }
  • 30. 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.
  • 31. 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.
  • 32. What we really want to do Display those confounded tweets! $tweets = $.getJSON('http://search.twitter.com/search.json? callback=?', query, function(tweets){ displayTweets(tweets); }); }
  • 33. Display tweets OK, it kinda does the same thing: function displayTweets(tweets) { console.debug(tweets.results); }
  • 34. 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');
  • 35. 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>'); }
  • 36. You and your console.debug!
  • 37. And what each tweet 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 I don’t want to redirect to twitter.com. I want to make each of my links become a search.
  • 42. Add a new function function triggerTweets(linked) { target = linked.html().replace('[#@]', ''); $("#whichTweet").val(target); getTweets(); return false; }
  • 43. Link it in your code. $("#tweetHolder a").click(function(){ return triggerTweets($(this)); });
  • 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. Advanced Tools More to life 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 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
  • 48. Know your Options There are other code libraries and toolkits Dojo Prototype MooTools YUI Google Closure Sencha (ExtJS)
  • 49. 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
  • 50. 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
  • 51. Summary What does it all mean?!?
  • 52. 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!
  • 53. Questions? http://spkr8.com/t/7912 @brianarn @teampoop brianarn@gmail.com markie@teampoop.com

Notas del editor

  1. \n
  2. \n
  3. May refer to information as &apos;data&apos; throughout the presentation - effectively synonymous for our purposes\n
  4. Undefined means the variable does not have a value yet, null means it is expressly set to a known empty value of sorts\n
  5. Strings can be single or double, doesn&apos;t matter\nAll numbers are IEEE 754 doubles, no integer types\n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n