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

JavaScript Libs Very Quick Guide

JavaScript Libs Very Quick Guide

Simple introduce JavaScript libs and frameworks.

Albert Shih

May 30, 2012
Tweet

More Decks by Albert Shih

Other Decks in Programming

Transcript

  1.  jQuery  jQuery UI  YUI  NodeJS 

    Mojito  CoffeeScript  Underscore.js  RequireJS  Backbone.js  Knockout.js  Ember.js  Angular.js
  2. divs = document.getElementByTagName(‘div’); for(int i = 0; I < divs.length;

    i++){ div[i].style.display = ‘none’; } JavaScript $(“div”).hide(); jQuery
  3. HTML <p>Click or double click here</p> jQuery $("p").bind("click", function(event){ var

    str = "(" + event.pageX + ", " + event.pageY + " )"; $("span").text("Click happend: " + str);}); $("p").bind("dblclick", function(){ $("span").text("Double-click happend: " + this.nodeName); }); Demo
  4. HTML <p>If you click on this paragraph, you'll see it

    just fade away.</p> jQuery $("p").click(function(){ $("p").fadeOut("slow"); }); Demo
  5. The functions and methods therein allow us to load data

    from the server without a browser page refresh.
  6. jQuery $('button[name="getImage"]').click(function(){ $.getJSON("http://api.flickr.com/services/feeds /photos_public.gne?jsoncallback=?", { tags: "cat", tagmode: "any", format:

    "json" }, function(data){ $.each(data.items, function(i, item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if(i == 3) return false; });}); }); Demo
  7. Add hover by grabing buttons with .ui-state-default and attach hover

    class. UI Classes Quick Tip $(“.ui-state-default”).hover( function(){ $(this).addClass(“ui-state-hover”);}, function(){ $(this).removeClass(“ui-state-hover”);} );
  8. HTML <div id="tabs"> <ul> <li><a href="#tabs-1">Nunc tincidunt</a></li> ... <li><a href="#tabs-3">Aenean

    lacinia</a></li>... </ul> <div id="#tabs-1"> ...</div> ... <div id="#tabs-1"> ...</div>... </div> jQuery $(function() { $( "#tabs" ). tabs(); }); Demo
  9. YUI.add (“editor”, function(Y) { }, require: [“ModuleNeed 1”, “ModuleNeed 2”]);

    //Y means YUI instance function Editor() { //Object constructor } //Push constructor to global Y.Editor = Editor;
  10. Code will execute when called, not executed when push into

    pages. Isolate codes, ignore dependencies order
  11. Just assign the module name then use it. YUI().use (“editor”,

    function(Y){ //This callback means all modules is loaded //Can create Y.editor object }); var editor = new Y.Editor();
  12. Get YUI modules loaded in one HTTP request from Yahoo!'s

    CDN <script src="http://yui.yahooapis.com/combo? <Module1 File Path> & <Module2 File Path> & <Module3 File Path> & … </script>
  13. In very short code to load module YUI.use(‘datatable’, function(Y) {

    alert(Y.Datatable); }); Disperse modules into three request and download parallel:  YUI Seed  CSS  Javasceipt Modules
  14. Node’s goal is to provide an easy way to build

    scalable network programs. -nodejs.org
  15.  JSON APIs  AJAX Sigle Page Application (Gmail etc.)

     Unix Tool  Streaming Data  Real Time Application (Twitter etc.)
  16.  Server-side JavaScript applications  Command line tools  Desktop

    GUI-based applications  Hybrid applications (Titanium, Adobe AIR)
  17. hello.js exports.world = function(){ return ‘Hello World’; }; main.js var

    hello = require(‘./hello’); var sys = require(‘sys’); sys.puts(hello.world()); Command $node main.js Hello World
  18. var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type':

    'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); Command % node example.js Server running at http://127.0.0.1:1337/
  19. 1 application requires = Objective C Java C .NET C++

    This is slow, time consuming and expensive!!
  20. 1 Language / Codebase for all devices. Optimized high quality

    experience views for any device with any screen size
  21. A Mojit is an independent unit of execution that can

    be used inside a Mojito application. Controller Model View [HTML] Binder [JS] MVC
  22. No { }, ( ), and ; If(age > 20){

    vote(); } //JavaScript If age > 20 vote() //CoffeeScript
  23. var say_hello; say_hello = function(guest1, guest2){ if(guest2 == null){ guest2

    = “Mary” } return “Hello” + guest1 + “and” + guest2; }; say_hello(“happybean”); //JavaScript say_hello = (guest1, guest2 = “Mary”) -> “Hello #{guest1} and #{guest2} say_hello “happybean” //CoffeeScript Function
  24. Collections- each - map - reduce - reduceRight - find

    - filter - reject - all - any - include - invoke - pluck - max - min - sortBy - groupBy - sortedIndex - shuffle - toArray - size Arrays - first - initial - last - rest - compact - flatten - without - union - intersection - difference - uniq - zip - indexOf - lastIndexOf - range Functions - bind - bindAll - memoize - delay - defer - throttle - debounce - once - after - wrap - compose Objects - keys - values - functions - extend - pick - defaults - clone - tap - has - isEqual - isEmpty - isElement - isArray - isObject - isArguments - isFunction - isString - isNumber - isFinite - isBoolean - isDate - isRegExp - isNaN - isNull - isUndefined Utility - noConflict - identity - times - mixin - uniqueId - escape - result - template Chaining - chain - value
  25. Plays nice with others  Does not modify built-in object

     Delegates to built-in functions if present
  26. Object-Oriented Style: _(stooges).pluck(‘name’) Functional Style: _.pluck(stooges , ‘name’) var stooges

    = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]; => ["moe", "larry", "curly"]
  27.  Fills in holes in the language  Provides functional

    support  Makes you happier writing JavaScript
  28.  Functions are objects  Functions are values  Can

    be assigned to a variable  Can be passed to another function as an argument  Can be returned by a function
  29. define( ‘account’, [‘service’, ‘pubsub’], function (service, pubsub){ //do something //export

    public APIs return{ signin: function() { /*… */ }, signout: function() { /*… */ }, … }; } };
  30. require( [ ‘order! lib/jQuery/jquery-min’ , ‘order! lib/underscore/underscore-min’ , ], function

    () { //This callback is called after the two libs finish loading. }
  31.  No pollution to global scope  Everything is organized

    in module  Compile CoffeeScript on the fly  … etc
  32.  Lots of modules  Lots of files  Lots

    of requests  Low performance
  33. var list = “”; $.each(data, function (index, value){ list +=

    “<li id=“\”item – “ + value.Id +”\”>” + value.Name + “</li>”; }); $(“ul”).append(list);
  34. “It’s all too easy to create JavaScript applications that end

    up as tangled piles of jQuery selectors and callbacks.”
  35.  Model providing key-value binding, custom events  Connects Model

    and Collection over a RESTful JSON interface  Views providing declarative event handling  Collection with a rich API of enumerable function
  36. Model  Fetch  HTTP GET /url  Save(new) 

    HTTP POST /url  Save  HTTP PUT /url/id  Destroy  HTTP DELETE /url/id
  37. var Item = Backbone.Model.extend({ idAttribute: “Id”, urlRoot: “/Items” }); var

    item = new Item() item.set([ Name: “happybean” ]); //trigger change Item.save(); //trigger sync
  38. var Items = new Items(); var listView = new ListView({

    collection:items }); Items.fetch();
  39. Pros  Strong community and lots of momentum.  Underscore.js

    (which it uses heavily) is also a great framework.
  40. Cons  Lacks strong abstractions and leaves something to be

    desired.  The entire framework is surprisingly lightweight and results in lots of boilerplate.  The larger an application becomes, the more this becomes apparent.
  41.  Model Defines the data structure  ViewModel Adapts the

    model for presentation  View Presents the data in the UI
  42.  Initialization of observable properties name = ko.observable(“Jon”); age =

    ko.observable(24);  Getter and setter are automatically generated for the properties name() //print “Jon” name(“Robert”) //sets name to “Robert”
  43. View <p>First name: <input data-bind="value: firstName" /></p> <p>Last name: <input

    data-bind="value: lastName" /></p> <h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
  44. View Model var ViewModel = function(first, last) { this.firstName =

    ko.observable(first); this.lastName = ko.observable(last); this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); , this); }; ko.applyBindings(new ViewModel("Planet", "Earth"));
  45. Don't waste time making trivial choices. Ember.js incorporates common idioms

    so you can focus on what makes your app special, not reinventing the wheel.
  46. Ember.js is built for productivity. Designed with developer ergonomics in

    mind, its friendly APIs help you get your job done— fast.
  47.  Flexible, observable, extensible objects  No routing mechanism 

    Unified App namespace  No explicit Models and Controllers
  48. MyApp.president = Ember.Object.create({ name: “Barack Obama” }); MyApp.country = Ember.Object.create({

    presidentNameBinding: 'MyApp.president.name' }); // Later, after Ember has resolved bindings... MyApp.country.get('presidentName'); // "Barack Obama"
  49. MyApp.president = Ember.Object.create({ firstName: “Barack”, lastName: “Obama”, fullName: function() {

    return this.get(‘firstName’) + ‘ ‘ + this.get(‘lastName’); //Call this flag to mark the function as a properties }.property() }); MyApp.president.get(‘fullName’); //Barack Obama
  50. Increase the level of abstraction Helps to write less code

    Make your app testable Works well together with other libs Helps to design and maintain big apps
  51. Angular is what HTML would have been if it was

    designed for building web - applications
  52. jQuery is for manipulation DOM and Angular is more for

    web-app frameworks with data binding
  53. Pros  Very well thought out with respect to template

    scoping and controller design  Has a dependency injection system (IOC)  Supports a rich UI-Binding syntax to make things like filtering and transforming values a breeze
  54. Cons  Codebase appears to be fairly sprawling and not

    very modular.  Views are not modular enough
  55. Framework UI Bindings Composed Views Web Presentation Layer Plays Nicely

    With Others Backbone.js ✗ ✗ ✓ ✓ Knockout.js ✓ ✗ ✓ ✓ Ember.js ✓ ✓ ✓ ✓ Angular.js ✓ ✗ ✓ ✓