jQuery secrets
Bastian Feder              IPC 2011
lapistano@php.net     th
                    10 October 2011
Me, myself & I

 JavaScript since 2002
 Trainer & coach
 Opensource addict
  PHP manual translations
  FluentDOM
  phpDox
  ...
Utilities
Saving the state

 jQuery.data( element, key[, value] )
   Store any kind of information on a DOM
   element
   Circular references avoided
   Low level function use
   $( element ).data( key[, value] ) instead.
Removing the state

 jQuery.removeData( element[, key] )
  Low level function use
  $( element ).removeData( [key] )
  instead.
  Removes all data if no key is passed.
State example

 var $logo = $('#jq-siteLogo');

 $(document).data('logo', $logo);

 $logo.detach();

 $('#content').before($(document).data('logo'));

 $(document).removeData('logo');
Hidden events

 getData[.namespace]
 Emitted, when the content is read.
 setData[.namespace]
 Emitted, when the content is set or reset.
 changeData[.namespace]
 Emitted, when the content has been changed.
 Comes always in hand with the setData event.
Hidden events                    (II)


var foo = $('div');

foo.bind('changeData.data', function( event, key, value ) {

      var data = new Array(value);
      $('#activitystream').trigger('myCustomEvent', data);

});

foo.data('my.data', 'Tux is a mascott.');
Extending for the good

  jQuery.extend([deep], target[, object1][,objectN])

var empty = {};
var defaults = {
    validate : false,
    limit    : {max: 5, min: 1},
    name     : "foo"
};
var options = {
    validate : true,
    limit    : {max:10}
};
var settings = $.extend(true, empty, defaults, options);
User defined properties

 Register of translations
 Used by .attr( )
  jQuery.propFix = {
     for         : "htmlFor",
     class       : "className",
     …
  };

  jQuery.extend(
      jQuery.propFix,
      {uijgh : "ui-jeopardy-gameboard-header"}
  );
DOM attributes

 Applies for every entry in jQuery.attrFn
 (e.g. val, css, text, data, … )


 var tux = $("<div/>", {
     css : {background: '#AAA'},
     text : 'beastie'
 });

 $("div")['css']({background: '#BBB'});
AJAX
Shortcuts       (II)


 jQuery.getJSON(
   url[,data ][,callback(data, textStatus)] )
 jQuery.getScript(
   url[,success(data, textStatus)] )
Global AJAX events

 ajaxStart
 everytime a new request has been fired and no request s running

 ajaxStop
 everytime no request is running anymore

 ajaxComplete
 once for each completed request (success or failure)
Global AJAX events                            (II)


 ajaxError
 once for each failed request

 ajaxSuccess
 once for each successful request

 ajaxSend
 once for each request, but before the request is send
Global AJAX events                   (III)


 jQuery('#loadingIndicator').bind(
    "ajaxStart",
    function() {
       $(this).show();
    }
 );

 jQuery('#loadingIndicator').bind(
    "ajaxStop",
    function() {
       $(this).hide();
    }
 );
Events
Event binding

  .bind(type[, data], handler(event))
      'type' might also be an object


$('.clickable').bind({

  'click'     : function(event) { //callback },
  'mousedown' : function(event) { //callback }

});
Namespaces

$('.clickable').bind('click.namespace', function(e){});

$('.clickable').bind({

  'click.namespace': function(event) { //callback },
  'mousedown.namespace': function(event) { //callback }

});

$('.clickable').unbind('.namespace');
Selfdefined speeding

jQuery.extend(
   jQuery.fx.speeds,
   {
      slow     : 600,
      fast     : 200,
      _default : 400
   },
   { slowmotion: 1000 }
);

$('#clickme').click(function() {
  $('#book').fadeIn('slowmotion');
});
Extending
 jQuery
jQuery plugins

  jQuery.error( message )

jQuery.prototype.error = function( message, errorcode ) {
  var error = [];
  error['msg'] = message;
  error['code'] = errorcode;
  if (typeof console != undefined) {
    console.error(error)
    return;
  }
}
jQuery UI

jQuery.extend('ui.autosuggest.prototype, {
  _search: function( value ) {
    // always save the actual value,
    // not the one passed as an argument
    this.term = this.element
      .addClass( "ui-autocomplete-loading"
      .val();

      this.source( { term: value }, this.response );
});
Questions
@lapistano

lapistano@php.net
Slides'n contact

 Please comment the talk on joind.in
   http://joind.in/3833
 Slides
   http://slideshare.net/lapistano
 Email:
   lapistano@php.net
License

 This set of slides and the source code
 included
   in the download package is licensed under
 the

 Creative Commons Attribution-
 Noncommercial-Share Alike 2.0 Generic
 License

jQuery secrets

  • 1.
    jQuery secrets Bastian Feder IPC 2011 lapistano@php.net th 10 October 2011
  • 2.
    Me, myself &I JavaScript since 2002 Trainer & coach Opensource addict PHP manual translations FluentDOM phpDox ...
  • 3.
  • 4.
    Saving the state jQuery.data( element, key[, value] ) Store any kind of information on a DOM element Circular references avoided Low level function use $( element ).data( key[, value] ) instead.
  • 5.
    Removing the state jQuery.removeData( element[, key] ) Low level function use $( element ).removeData( [key] ) instead. Removes all data if no key is passed.
  • 6.
    State example var$logo = $('#jq-siteLogo'); $(document).data('logo', $logo); $logo.detach(); $('#content').before($(document).data('logo')); $(document).removeData('logo');
  • 7.
    Hidden events getData[.namespace] Emitted, when the content is read. setData[.namespace] Emitted, when the content is set or reset. changeData[.namespace] Emitted, when the content has been changed. Comes always in hand with the setData event.
  • 8.
    Hidden events (II) var foo = $('div'); foo.bind('changeData.data', function( event, key, value ) { var data = new Array(value); $('#activitystream').trigger('myCustomEvent', data); }); foo.data('my.data', 'Tux is a mascott.');
  • 9.
    Extending for thegood jQuery.extend([deep], target[, object1][,objectN]) var empty = {}; var defaults = { validate : false, limit : {max: 5, min: 1}, name : "foo" }; var options = { validate : true, limit : {max:10} }; var settings = $.extend(true, empty, defaults, options);
  • 10.
    User defined properties Register of translations Used by .attr( ) jQuery.propFix = { for : "htmlFor", class : "className", … }; jQuery.extend( jQuery.propFix, {uijgh : "ui-jeopardy-gameboard-header"} );
  • 11.
    DOM attributes Appliesfor every entry in jQuery.attrFn (e.g. val, css, text, data, … ) var tux = $("<div/>", { css : {background: '#AAA'}, text : 'beastie' }); $("div")['css']({background: '#BBB'});
  • 12.
  • 13.
    Shortcuts (II) jQuery.getJSON( url[,data ][,callback(data, textStatus)] ) jQuery.getScript( url[,success(data, textStatus)] )
  • 14.
    Global AJAX events ajaxStart everytime a new request has been fired and no request s running ajaxStop everytime no request is running anymore ajaxComplete once for each completed request (success or failure)
  • 15.
    Global AJAX events (II) ajaxError once for each failed request ajaxSuccess once for each successful request ajaxSend once for each request, but before the request is send
  • 16.
    Global AJAX events (III) jQuery('#loadingIndicator').bind( "ajaxStart", function() { $(this).show(); } ); jQuery('#loadingIndicator').bind( "ajaxStop", function() { $(this).hide(); } );
  • 17.
  • 18.
    Event binding .bind(type[, data], handler(event)) 'type' might also be an object $('.clickable').bind({ 'click' : function(event) { //callback }, 'mousedown' : function(event) { //callback } });
  • 19.
    Namespaces $('.clickable').bind('click.namespace', function(e){}); $('.clickable').bind({ 'click.namespace': function(event) { //callback }, 'mousedown.namespace': function(event) { //callback } }); $('.clickable').unbind('.namespace');
  • 20.
    Selfdefined speeding jQuery.extend( jQuery.fx.speeds, { slow : 600, fast : 200, _default : 400 }, { slowmotion: 1000 } ); $('#clickme').click(function() { $('#book').fadeIn('slowmotion'); });
  • 21.
  • 22.
    jQuery plugins jQuery.error( message ) jQuery.prototype.error = function( message, errorcode ) { var error = []; error['msg'] = message; error['code'] = errorcode; if (typeof console != undefined) { console.error(error) return; } }
  • 23.
    jQuery UI jQuery.extend('ui.autosuggest.prototype, { _search: function( value ) { // always save the actual value, // not the one passed as an argument this.term = this.element .addClass( "ui-autocomplete-loading" .val(); this.source( { term: value }, this.response ); });
  • 24.
  • 25.
    Slides'n contact Pleasecomment the talk on joind.in http://joind.in/3833 Slides http://slideshare.net/lapistano Email: lapistano@php.net
  • 26.
    License This setof slides and the source code included in the download package is licensed under the Creative Commons Attribution- Noncommercial-Share Alike 2.0 Generic License