Advanced jQuery

1,242 views

Published on

Sergio Pereira's Advanced jQuery slide deck.

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

No Downloads
Views
Total views
1,242
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • for this talk I'll assume you all know the basics of jQuery and have been using it for DOM manipulation and Ajax calls. I'll show some of the other things in jq that could be labeled as intermediate to advanced. I'll try to highlight anything that is new in 1.7.\n
  • for this talk I'll assume you all know the basics of jQuery and have been using it for DOM manipulation and Ajax calls. I'll show some of the other things in jq that could be labeled as intermediate to advanced. I'll try to highlight anything that is new in 1.7.\n
  • I normally don't like presentations that are all about tricks and trips because it's hard to keep track of everything. I'll try to keep the machine gun quiet but I still wanted to highlight a handful of helpful gems in jq.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • DEMO!\n
  • \n
  • DEMO!\n
  • \n
  • \n
  • \n
  • DEMO!\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • this should be familiar to most of you. The Select() Linq extension does that for IEnumerables in .net. We do the conversion with callback.\n
  • this should be familiar to most of you. The Select() Linq extension does that for IEnumerables in .net. We do the conversion with callback.\n
  • But there are a few things to note in the callback function.\n
  • \n
  • Event handling is one of the main reasons we use jquery for...\n
  • It makes it so easy to watch for an event of an element... just choose the element and...\n
  • Oh, that's that too. It's easy but it takes a little practice to pick the most efficient route. I'm sure a few of us still has to think about it or look up docs to choose the right one for the task.\n
  • both bind and live allow us to setup handlers for one or many elements in a single command. Select all the elements you want and attach the handler. main diff: dynamically added elements\n
  • unique elements: elements that don't have a similar purpose with any other element on the page.\n
  • OK, it was easy to figure out between the previous 2. But those two appear to do the same. Attach a handler for a selector.\nDiff: delegate() attaches a handler to the parent, not Doc. Syntax.\n
  • \n
  • on() can also take a data parameter that goes to event.data\n
  • \n
  • \n
  • global events\n
  • \n
  • DEMO!\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • DEMO!\n
  • \n
  • \n
  • \n
  • this is possible way to invoke a callback-based async function... note the two different callbacks, for success and error. note the duplication too.\n
  • it could get worse. look what would happen if useResult was also async... what if an error happens in useResult? another error callback?\n
  • see how much cleaner the code becomes when we introduce the deferred task object.\nWe can even subscribe later and it will fire immediately if the task has completed already. DEMO1!\n
  • the tasks allow us to compose more complicated scenarios without sacrificing too much the read-ability of the code.\n
  • \n
  • \n
  • DEMO2!\n
  • Internally jQuery can maintain queues of actions. One such queue is the one that allows effects to execute sequentially.\nThe promise command returns a deferred task that resolves when the queue empties.\n
  • \n
  • \n
  • \n
  • show github, show how files are split, show local repo, build\n
  • \n
  • \n
  • \n
  • \n
  • Advanced jQuery

    1. 1. Advan ced
    2. 2. Sergi oPereir
    3. 3. Sergio•http://sergiopereira.com/blog look•@sergiopereira•Chicago ALT.NET•Chicago Code
    4. 4. The Plan•not just Tips &Tricks but, yeah,some of those•overlooked jQueryfeatures•coding the jQuery
    5. 5. The PlanIs Subject To Change
    6. 6. QuickWins
    7. 7. end()breadcrumbs foryour navigation
    8. 8. end() Command<div class=menu> <ul> <li class=current>New</li> <li>Open...</li> <li>Print...</li> </ul></div><div class=menu> ...</div>
    9. 9. end() Command$(.menu).find(li) <div class=menu> <ul> <li class=current>New</li> <li>Open...</li> <li>Print...</li> </ul> </div> <div class=menu> ... </div>
    10. 10. end() Command$(.menu).find(li) .filter(.current) <div class=menu> <ul> <li class=current>New</li> <li>Open...</li> <li>Print...</li> </ul> </div> <div class=menu> ... </div>
    11. 11. end() Command$(.menu).find(li) .filter(.current) .end() <div class=menu> <ul> <li class=current>New</li> <li>Open...</li> <li>Print...</li> </ul> </div> <div class=menu> ... </div>
    12. 12. end() Command$(.menu).find(li) .filter(.current) .end().end() <div class=menu> <ul> <li class=current>New</li> <li>Open...</li> <li>Print...</li> </ul> </div> <div class=menu> ... </div>
    13. 13. Computedfor when a simple expression isn’t enough
    14. 14. Computed Values$(#buttons li) .css(margin-left, function(ix, val) { return ix*10; });
    15. 15. Computed Values• attr(name, function(i,v){ })• prop(name, function(i,v){ })• val(function(i,v){ })• css(name, function(i,v){ })
    16. 16. Relative CSS incremental
    17. 17. Relative CSS$(#volumeUp).click(function(){ var $volBar = $(#volBar); var width = $volBar.css(width); //easy mistake $volBar.css(width, width + 10);});
    18. 18. Relative CSS$(#volumeUp).click(function(){ $(#vol).css(margin-left, +=10);});
    19. 19. data()goodbye memory leaks
    20. 20. data() Storagevar myForm = $(#myform)[0];var formResult = { errors: validateForm(myForm), form: myForm};myForm.result = formResult;//later...var result = $(#myform)[0].result;if(result.errors.length){ alert(Fix the errors.);}
    21. 21. data() Storagevar formResult = { errors: validateForm(myForm), form: $(#myform)};$(#myform).data(result, formResult);//later...var result = $(#myform).data(result);if(result.errors.length){ alert(Fix the errors.);}
    22. 22. data() Storage <ul> <li data-movie-id="131">Crash</li> <li data-movie-id="722">Up</li> </ul>var id = $(li:first).data(movieId);// ==> id == 131
    23. 23. data() Storagedata attributes•will try to usecorrect data type•parses JSONvalues
    24. 24. map() Utilityprojections for your arrays
    25. 25. map() Utility array-like: has most of whatsneeded to be used as an array var arrayLike = { length: 2, 0: first, 1: second };
    26. 26. map() Utility bonus utility: makeArray()var arr = $.makeArray(arrayLike);// ==> [first,second]
    27. 27. map() Utilityvar users = getUsersArray();var emails = $.map(users, function(user, i){ return user.profile.email; });
    28. 28. map() Utilityvar users = getUsersArray();var emails = $.map(users, function(user, i){ return user.profile.email; });
    29. 29. map() Utility the callback function•return new valuefor the position•return null toexclude that position
    30. 30. reQuick ca• p end(): avoidunnecessarytraversals•computedattributes•relative CSSattributes
    31. 31. EventHandling
    32. 32. jQuerydetermine which element and...
    33. 33. bind(), live(), delegate(),well, yes - choices
    34. 34. bind() vs. live()$(#container .action) .bind(click, function(){ //do stuff here });//same as: $(#container .action)// .click(function(){...});//prefer:$(#container .action) .live(click, function(){ //do stuff here });
    35. 35. bind() vs. live()•live(): moreefficient usage•live(): works foradded elements•live(): forces youto deal with the
    36. 36. live() vs. delegate()$(#container .action) .live(click, doStuff);$(#container) .delegate(.action,click, doStuff);
    37. 37. live() vs. delegate() • live(): syntax is slightly easier • live(): attaches to document • delegate(): attaches closer
    38. 38. Everything vs. on()$(#close).bind(click, closeWindow);$(#close).on(click, closeWindow);$(.popup).delegate( .closeBtn,click, closePopup);$(.popup).on( click,.closeBtn, closePopup);
    39. 39. Everything vs. on()$(#close).bind(click, closeWindow);$(#close).on(click, closeWindow);$(.popup).delegate( .closeBtn,click, closePopup);$(.popup).on( click,.closeBtn, closePopup); 1.7
    40. 40. Customthey remove tight coupling
    41. 41. Custom Events$(#widget).on(start, function(){ //do stuff});//elsewhere, maybe in another js file:$(#widget).on(start, function(){ //do other stuff});//when appropriate:$(#widget).trigger(start);
    42. 42. Custom Events$(#btn1).on(lock, function(){ $(this).prop(disabled, true);});//elsewhere, maybe in another js file:$(#toolbar).on(lock, function(){ $(this).find(.icon).remove();});//when appropriate:$.event.trigger(lock);
    43. 43. proxy()lets put this in context
    44. 44. proxy() Utilityvar f = $.proxy(obj, doSomething);var f = $.proxy(obj.doSomething, obj);
    45. 45. reEvent ca• p pick the rightbinding command•delegate() overlive()•on() unifies it all•decouple with
    46. 46. Extensio ns
    47. 47. Customthe abc of jQuery mastery
    48. 48. Custom Commands function stripeTable(table, alt) { $(table) .find(tr:odd) .addClass(alt||alternate); } //... var table = $(#mytable)[0]; stripeTable(table, altRow);
    49. 49. Custom Commands jQuery.fn.stripe = function(alt) { this .children(:odd) .addClass(alt||alternate); return this; }; //... $(#mytable).stripe(altRow);
    50. 50. Custom Commands jQuery.fn.stripe = function(alt) { this .children(:odd) .addClass(alt||alternate); return this; }; //... $(#mytable).stripe(altRow);
    51. 51. Customexpressive means readable
    52. 52. Custom$.expr[:].myfilter = function(el) { //return true if el(ement) matches}//...$(div:myfilter).slideDown();
    53. 53. reExtensions ca p•commands•expressions•events
    54. 54. 1.5Deferred Object
    55. 55. Futures,decouple the task from what you do with its outcome
    56. 56. Tidy CallbacksstartLongProcess( function(result){ useResult(result); logCompletion(result); }, function(error){ logCompletion(result); logFailure(error); });
    57. 57. Tidy CallbacksstartLongProcess( function(result){ useResult(result, function(res2){ updateScreen(res2); }); logCompletion(result); }, //...);
    58. 58. Tidy Callbacksvar task = startLongProcess() .done(useResult) .always(logCompletion) .fail(logFailure);doSomethingElse();//time passes...task.fail(function(){ alert(error);});
    59. 59. Tidy Callbacksvar task = startLongProcess() .always(logCompletion) .fail(logFailure);$.when(task, otherTask) .then(function(args1, args2){ useResult(args1[0]) .done(updateScreen); });
    60. 60. Deferreds in time to relearn some features
    61. 61. Ajaxvar fetch = $.get(/data.aspx) .done(validateResponse) .done(doSomething) .done(doMoreStuff) .fail(reportError);fetch.fail(resetUI);
    62. 62. when() Utility$.when( $.get(/somedata), $.get(/moredata), $.post(/updatedata, data), someOtherDeferred) .then(function(){ alert(all done); });
    63. 63. promise()$(.widget) .first().fadeOut(500).end() .last().fadeOut(1000).end() .promise() //default: fx queue .done(function(){ //do something... });
    64. 64. reDeferred ca p•common way forcallbacks•returned by jQueryAjax•for commandqueues too
    65. 65. The True Source
    66. 66. github https://github.com/jquery
    67. 67. github https://github.com/jquery
    68. 68. Build It, Runcheck out QUnit
    69. 69. Question s?
    70. 70. Reference•http://api.jquery.com•Paul Irishs articlesand videos
    71. 71. Thank You

    ×