Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Pocket Knife JS

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →

Pocket Knife JS

Overview of some js micro frameworks.
#codebits2011

Diogo Antunes

November 11, 2011

Transcript

80 slides
  1. KILL ALL HUMANS! I. Robot Forensic Anthropologist Pocket Knife JS

    November 10, 2011 Friday, November 11, 11
  2. Who am I • Diogo Antunes • JavaScript developer @

    SAPO • @dicode Friday, November 11, 11
  3. Who am I • Diogo Antunes • JavaScript developer @

    SAPO • @dicode • http://js.sapo.pt Friday, November 11, 11
  4. JS World • Wonderful things are happening • Lot’s of

    new code, snippets • Great community • Always looking forward Friday, November 11, 11
  5. Why? • JS is cool • Lot to learn •

    Lot to innovate Friday, November 11, 11
  6. Pocket Knife • There are code out there that can

    help • You can use it, fork it, re-write it • but you’ll definitely learn a lot digging in Friday, November 11, 11
  7. Mustache • Logic-less templates with JavaScript • you can render

    templates in your browser, or rendering server-side stuff with node.js, use it for rendering stuff in CouchDB’s views • Plugins for jQuery, Dojo, Yui, CommonJS, qooxdoo Friday, November 11, 11
  8. Mustache var view = { "name": "Bill", "address": { "street":

    "801 Streetly street", "city": "Boston", "state": "MA", "zip" "02101" } } var template = '<h1>Contact: {{name}}</h1> {{#address}} <p>{{street}}</p> <p>{{city}}, {{state}} {{zip}}</p> {{/address}}'; var html = Mustache.to_html(template, view); <h1>Contact: Bill</h1> <p>801 Streetly street</p> <p>Boston, MA 02101</p> Friday, November 11, 11
  9. Lab.js • Loading And Blocking JavaScript • Load JS from

    anywhere at anytime • You can even load LABjs dynamically Friday, November 11, 11
  10. Lab.js <script src="framework.js"></script> <script src="plugin.framework.js"></script> <script src="myplugin.framework.js"></script> <script src="init.js"></script> <script>

    $LAB .script("framework.js").wait() .script("plugin.framework.js") .script("myplugin.framework.js").wait() .script("init.js").wait(); </script> Friday, November 11, 11
  11. require.js • plugins for jquery, dojo or node.js • RequireJS

    is a JavaScript file and module loader. • It is optimized for in-browser use, but it can be used in other JavaScript environments Friday, November 11, 11
  12. require.js <!DOCTYPE html> <html> <head> <title>My Sample Project</title> <!-- data-main

    attribute tells require.js to load scripts/main.js after require.js loads. --> <script data-main="scripts/main" src="scripts/require.js"></script> </head> <body> <h1>My Sample Project</h1> </body> </html> project-directory/ project.html scripts/ main.js require.js helper/ util.js Friday, November 11, 11
  13. require.js <!DOCTYPE html> <html> <head> <title>My Sample Project</title> <!-- data-main

    attribute tells require.js to load scripts/main.js after require.js loads. --> <script data-main="scripts/main" src="scripts/require.js"></script> </head> <body> <h1>My Sample Project</h1> </body> </html> require(["helper/util"], function() { //This function is called when scripts/helper/util.js is loaded. }); Friday, November 11, 11
  14. zepto.js • minimalist JavaScript framework for mobile WebKit browsers, with

    a jQuery-compatible syntax. • ~5kb • has almost everything Friday, November 11, 11
  15. émile • Stand-alone CSS animation JavaScript mini-framework • Doesn't need

    a JavaScript framework • Full set of CSS properties for animation (length-based and colors) • Easing and callbacks • Less than 50 lines of code Friday, November 11, 11
  16. shifty • A teeny tiny tweening engine in JavaScript •

    low-level library meant to be encapsulated by higher-level tools Friday, November 11, 11
  17. shifty - do’s • Tweening of Numbers. • Extensibility hooks

    for the tweening. Friday, November 11, 11
  18. shifty var myTweenable = new Tweenable(); myTweenable.tween( from, to );

    myTweenable.tween( from, to, duration, callback, easing ); myTweenable.tween({ from: { }, // Object. Contains the properties to tween. Must all be `Number`s. Note: This object's properties are modified by the tween. to: { }, // Object. The "destination" `Number`s that the properties in `from` will tween to. duration: 1000, // Number. How long the tween lasts for, in milliseconds. easing: 'linear', // String. Easing equation to use. You can specify any easing method that was attached to `Tweenable.prototype.formula`. start: function () {}, // Function. Runs as soon as the tween begins. Handy when used with the `queue` extension. step: function () {}, // Function. Runs each "frame" that the tween is updated. callback: function () {} // Function. Runs when the tween completes. }); Friday, November 11, 11
  19. swipe.js • lightweight mobile slider with 1-to-1 touch movement <div

    id='slider'> <ul> <li style='display:block'></li> <li style='display:none'></li> <li style='display:none'></li> <li style='display:none'></li> <li style='display:none'></li> </ul> </div> Friday, November 11, 11
  20. swipe.js window.mySwipe = new Swipe(document.getElementById('slider'), { startSlide: 2, speed: 400,

    auto: 3000, callback: function(event, index, elem) { // do something cool } }); Friday, November 11, 11
  21. Jaguar • standalone CSS selector engine developed for the Shrike

    JavaScript library • 0 Regexes • 0 Try-catch blocks • No browser sniffing • Only 3kb (minified and gzipped) Friday, November 11, 11
  22. Jaguar Jaguar.search(String selector[, DOMElement|DOMDocument context]) // Or simply: Jaguar(String selector[,

    DOMElement|DOMDocument context]) Jaguar.match(Jaguar('#id')[0], '#id') // true Jaguar.match(Jaguar('#cake')[0], '.edible') // hopefully true Friday, November 11, 11
  23. underscore • functional programming • utility-belt library • think Prototype.js

    • without extending built-in • so fits great with jQuery or Zepto Friday, November 11, 11
  24. underscore var lyrics = [ {line : 1, words :

    "I'm a lumberjack and I'm okay"}, {line : 2, words : "I sleep all night and I work all day"}, {line : 3, words : "He's a lumberjack and he's okay"}, {line : 4, words : "He sleeps all night and he works all day"} ]; _(lyrics).chain() .map(function(line) { return line.words.split(' '); }) .flatten() .reduce(function(counts, word) { counts[word] = (counts[word] || 0) + 1; return counts; }, {}).value(); => {lumberjack : 2, all : 4, night : 2 ... } Friday, November 11, 11
  25. Backbone.js • supplies structure to JavaScript-heavy applications • Backbone's only

    hard dependency is Underscore.js. For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( > 1.4.2) or Zepto. Friday, November 11, 11
  26. Backbone.js var Sidebar = Backbone.Model.extend({ promptColor: function() { var cssColor

    = prompt("Please enter a CSS color:"); this.set({color: cssColor}); } }); window.sidebar = new Sidebar; var ItemView = Backbone.View.extend({ tagName: 'li' }); var item = new ItemView(); Friday, November 11, 11
  27. my-class • 100% no wrappers, same perfs as hand-written pure

    JS classes • not only a class implementation, it's mostly a class design Friday, November 11, 11
  28. my-class (function() { var Person = my.Class({ constructor: function(name) {

    this.name = name; }, sayHello: function() { console.log('Hello from ' + this.name + '!'); } }) var Dreamer = my.Class(Person, { constructor: function(name, dream) { Dreamer.Super.call(this, name); this.dream = dream; }, sayDream: function() { console.log('I dream of ' + this.dream + '!'); } }); var sylvester = new Dreamer('Sylvester', 'eating Tweety'); sylvester.sayHello(); sylvester.sayDream(); alert('See this page source & open your JS console'); })(); Friday, November 11, 11
  29. jXHR • clone-variant of the XMLHttpRequest object API • makes

    cross-domain JSON-P styled call Friday, November 11, 11
  30. jXHR function handleError(msg,url) { alert(msg); } function doit() { var

    x1 = new jXHR(); x1.onerror = handleError; x1.onreadystatechange = function(data){ if (x1.readyState === 4) { alert("Success:"+data.source); } }; x1.open("GET","jsonme.php?callback=?&data="+ encodeURIComponent(JSON.stringify({data:"my value 1"}))+ "&_="+Math.random()); x1.send(); } Friday, November 11, 11
  31. benchmark.js • works on nearly all JavaScript platforms • supports

    high-resolution timers • returns statistically significant results Friday, November 11, 11
  32. benchmark.js var suite = new Benchmark.Suite; // add tests suite.add('RegExp#test',

    function() { /o/.test('Hello World!'); }) .add('String#indexOf', function() { 'Hello World!'.indexOf('o') > -1; }) .add('String#match', function() { !!'Hello World!'.match(/o/); }) // add listeners .on('cycle', function(event, bench) { console.log(String(bench)); }) .on('complete', function() { console.log('Fastest is ' + this.filter('fastest').pluck('name')); }) // run async .run({ 'async': true }); Friday, November 11, 11
  33. mibbu • fast prototyping your Javascript game • displayed using

    Canvas or DOM mode • CSS animations Friday, November 11, 11
  34. Modernizr • feature detection with media queries and conditional resource

    loading • adds classes to html element to say if a certain feature is available • Modernizr JS object let’s you have a set of flags that help you building your code Friday, November 11, 11
  35. Modernizr if (Modernizr.geolocation) { //do whatever you want } <html

    class="js canvas canvastext geolocation rgba hsla no-multiplebgs borderimage borderradius boxshadow opacity no-cssanimations csscolumns no-cssgradients no-cssreflections csstransforms no-csstransforms3d no- csstransitions video audio cufon-active fontface cufon-ready"> Friday, November 11, 11
  36. system.js • Javacript object with the user's system information document.body.innerHTML

    = [ '<strong>Browser</strong> ' + System.browser, '<strong>OS</strong> ' + System.os, '', '<strong>Canvas</strong> ' + System.support.canvas, '<strong>Local storage</strong> ' + System.support.localStorage, '<strong>File API</strong> ' + System.support.file, '<strong>FileSystem API</strong> ' + System.support.fileSystem, '<strong>RequestAnimationFrame</strong> ' + System.support.requestAnimationFrame, '<strong>Session storage</strong> ' + System.support.sessionStorage, '<strong>WebGL</strong> ' + System.support.webgl, '<strong>Worker</strong> ' + System.support.worker ].join( '<br />' ); Friday, November 11, 11
  37. EventEmitter • you can listen for and emit events from

    what ever objects you choose • port of the node.js EventEmitter Friday, November 11, 11
  38. EventEmitter // Initialise the EventEmitter var ee = new EventEmitter();

    // Initialise the listener function function myListener() { console.log('The foo event was emitted.'); } // Add the listener ee.addListener('foo', myListener); // Emit the foo event ee.emit('foo'); // The listener function is now called // Remove the listener ee.removeListener('foo', myListener); // Log the array of listeners to show that it has been removed console.log(ee.listeners('foo')); Friday, November 11, 11
  39. Augment.js • Enables use of modern JavaScript by augmenting built

    in objects with the latest JavaScript methods Friday, November 11, 11
  40. gowiththeflow • asynchronous flow-control micro library • asynchronous code is

    executed, sequentially or in parallel Friday, November 11, 11
  41. gowiththeflow var Flow = require('gowiththeflow') Flow().seq(function(next){ console.log("step 1: started, it

    will last 1sec"); setTimeout(function(){ console.log("step 1: 1sec expired. Step 1 completed"); next(); }, 1000); }).seq(function(next){ console.log("step 2: run after step1 has been completed"); }) Friday, November 11, 11
  42. Ender • Build only what you need, when you need

    it. • Lightweight, expressive, familiar. • think of it as NPM's little sister • if one library goes bad or unmaintained, it can be replaced with another Friday, November 11, 11
  43. Ender ender build domready qwery underscore $('#content a.button') .bind('click.button', function

    (e) { $(this).data('clicked', true).unbind() e.preventDefault() }) .css({ opacity: 1 , color: 'red' }) .fadeOut(250) $.map(['a', 'b', 'c'], function (letter) { return letter.toUpperCase() }) $.ajax('/data', function (resp) { $('#content').html(resp) }) Friday, November 11, 11
  44. Ender // IN THE BROWSER // Require packages to access

    them as raw packages var _ = require('underscore') , _.each([1, 2, 3], alert) // Access methods augmented directly to the $ $.ready(function () { $([1, 2, null, 3]) .filter(function (item) { return item }) .each(alert) }) Friday, November 11, 11
  45. full purpose frameworks • jQuery • Dojo • Prototype.js •

    YUI • LibSAPO.js • etc. Friday, November 11, 11

More Decks by Diogo Antunes

Other Decks in Programming