Pocket Knife JS

2,551 views

Published on

Overview of some js micro frameworks.
#codebits2011

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

No Downloads
Views
Total views
2,551
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
21
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide

Pocket Knife JS

  1. 1. KILL ALL Pocket Knife HUMANS! JS I. Robot Forensic Anthropologist November 10, 2011Friday, November 11, 11
  2. 2. Who am IFriday, November 11, 11
  3. 3. Who am I • Diogo AntunesFriday, November 11, 11
  4. 4. Who am I • Diogo Antunes • JavaScript developer @ SAPOFriday, November 11, 11
  5. 5. Who am I • Diogo Antunes • JavaScript developer @ SAPO • @dicodeFriday, November 11, 11
  6. 6. Who am I • Diogo Antunes • JavaScript developer @ SAPO • @dicode • http://js.sapo.ptFriday, November 11, 11
  7. 7. JS World • Wonderful things are happening • Lot’s of new code, snippets • Great community • Always looking forwardFriday, November 11, 11
  8. 8. Why? • JS is cool • Lot to learn • Lot to innovateFriday, November 11, 11
  9. 9. 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 inFriday, November 11, 11
  10. 10. Going deepFriday, November 11, 11
  11. 11. TemplatingFriday, November 11, 11
  12. 12. 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, qooxdooFriday, November 11, 11
  13. 13. Mustache var view = { "name": "Bill", "address": { "street": "801 Streetly street", "city": "Boston", "state": "MA", <h1>Contact: Bill</h1> "zip" "02101" <p>801 Streetly street</p> } <p>Boston, MA 02101</p> } var template = <h1>Contact: {{name}}</h1> {{#address}} <p>{{street}}</p> <p>{{city}}, {{state}} {{zip}}</p> {{/address}}; var html = Mustache.to_html(template, view);Friday, November 11, 11
  14. 14. LoadersFriday, November 11, 11
  15. 15. Lab.js • Loading And Blocking JavaScript • Load JS from anywhere at anytime • You can even load LABjs dynamicallyFriday, November 11, 11
  16. 16. 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
  17. 17. 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 environmentsFriday, November 11, 11
  18. 18. require.js project-directory/ project.html scripts/ main.js require.js helper/ util.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>Friday, November 11, 11
  19. 19. 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
  20. 20. webkit-basedFriday, November 11, 11
  21. 21. zepto.js • minimalist JavaScript framework for mobile WebKit browsers, with a jQuery-compatible syntax. • ~5kb • has almost everythingFriday, November 11, 11
  22. 22. zepto.js $(document).ready(function(){ ... }); $.isFunction(function), $.isObject(object), $.isArray(array); $(some selector).bind(click, function(event){ ... });Friday, November 11, 11
  23. 23. animationFriday, November 11, 11
  24. 24. émile • Stand-alone CSS animation JavaScript mini-framework • Doesnt need a JavaScript framework • Full set of CSS properties for animation (length-based and colors) • Easing and callbacks • Less than 50 lines of codeFriday, November 11, 11
  25. 25. émile • one method emile(element, style, options, after)Friday, November 11, 11
  26. 26. shifty • A teeny tiny tweening engine in JavaScript • low-level library meant to be encapsulated by higher-level toolsFriday, November 11, 11
  27. 27. shifty - do’s • Tweening of Numbers. • Extensibility hooks for the tweening.Friday, November 11, 11
  28. 28. shifty - dont’s • Keyframing. • Drawing. • Much else.Friday, November 11, 11
  29. 29. 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 objects 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
  30. 30. 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
  31. 31. 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
  32. 32. selectorsFriday, November 11, 11
  33. 33. 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
  34. 34. 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 trueFriday, November 11, 11
  35. 35. enhancementFriday, November 11, 11
  36. 36. underscore • functional programming • utility-belt library • think Prototype.js • without extending built-in • so fits great with jQuery or ZeptoFriday, November 11, 11
  37. 37. underscore var lyrics = [ {line : 1, words : "Im a lumberjack and Im okay"}, {line : 2, words : "I sleep all night and I work all day"}, {line : 3, words : "Hes a lumberjack and hes 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
  38. 38. MVCFriday, November 11, 11
  39. 39. Backbone.js • supplies structure to JavaScript-heavy applications • Backbones 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
  40. 40. 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
  41. 41. OOPFriday, November 11, 11
  42. 42. my-class • 100% no wrappers, same perfs as hand-written pure JS classes • not only a class implementation, its mostly a class designFriday, November 11, 11
  43. 43. (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) { my-class 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
  44. 44. communicationFriday, November 11, 11
  45. 45. jXHR • clone-variant of the XMLHttpRequest object API • makes cross-domain JSON-P styled callFriday, November 11, 11
  46. 46. 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
  47. 47. benchmarkingFriday, November 11, 11
  48. 48. benchmark.js • works on nearly all JavaScript platforms • supports high-resolution timers • returns statistically significant resultsFriday, November 11, 11
  49. 49. 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
  50. 50. gamesFriday, November 11, 11
  51. 51. mibbu • fast prototyping your Javascript game • displayed using Canvas or DOM mode • CSS animationsFriday, November 11, 11
  52. 52. mibbuFriday, November 11, 11
  53. 53. feature detectionFriday, November 11, 11
  54. 54. 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 codeFriday, November 11, 11
  55. 55. Modernizr <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"> if (Modernizr.geolocation) { //do whatever you want }Friday, November 11, 11
  56. 56. system.js • Javacript object with the users 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
  57. 57. eventsFriday, November 11, 11
  58. 58. EventEmitter • you can listen for and emit events from what ever objects you choose • port of the node.js EventEmitterFriday, November 11, 11
  59. 59. 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
  60. 60. polyfillsFriday, November 11, 11
  61. 61. Augment.js • Enables use of modern JavaScript by augmenting built in objects with the latest JavaScript methodsFriday, November 11, 11
  62. 62. Augment.js Array.prototype.every Array.prototype.filter Array.prototype.forEach Array.prototype.indexOf Array.isArray Date.now Date.prototype.toJSON Date.prototype.toISOString Function.prototype.bind Object.keys String.prototype.trimFriday, November 11, 11
  63. 63. State MachineFriday, November 11, 11
  64. 64. gowiththeflow • asynchronous flow-control micro library • asynchronous code is executed, sequentially or in parallelFriday, November 11, 11
  65. 65. 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
  66. 66. what you just needFriday, November 11, 11
  67. 67. Ender • Build only what you need, when you need it. • Lightweight, expressive, familiar. • think of it as NPMs little sister • if one library goes bad or unmaintained, it can be replaced with anotherFriday, November 11, 11
  68. 68. Ender is not a JavaScript library.Friday, November 11, 11
  69. 69. 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
  70. 70. 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
  71. 71. full purpose frameworksFriday, November 11, 11
  72. 72. full purpose frameworks • jQuery • Dojo • Prototype.js • YUI • LibSAPO.js • etc.Friday, November 11, 11
  73. 73. why should I bother?Friday, November 11, 11
  74. 74. be a better developerFriday, November 11, 11
  75. 75. Make It Work Make It Right Make It FastFriday, November 11, 11
  76. 76. Do’s and don’tsFriday, November 11, 11
  77. 77. Wrap UpFriday, November 11, 11
  78. 78. Use it carefullyFriday, November 11, 11
  79. 79. Think for yourselfFriday, November 11, 11
  80. 80. ThanksFriday, November 11, 11

×