Presented by Arsalan AhmedjQuery Goodness – part 1
Different species than POCOsProperties added dynamically upon first useA typo creates a new property – yikes!Properties accessed via:	Dot notation (Object.Property)Subscript notation (Object[‘Property’])Literal syntax:varsomeObj = { someProp: ‘some value’, otherProp: 2 };Variables are properties. Equivalent statements in the global scope:var prop = ‘x’; window.prop = ‘x’; prop = x;Objects in Javascript
Functions are also objectsFunctions can contain other functions!have properties!be assigned to a propertybe passed to a method and also returned from itSmoke and mirrors. Equivalent statements:function someFunc(someParam) { return ‘wow!’ }someFunc = function(someParam) { return ‘wow!’ }window. someFunc = function(someParam) { return ‘wow!’ }So what’s the deal with these functions?
Local variables stick aroundGreat way to avoid using global variablesAvoids potential naming conflictsExample:var f = function() {varartifactID = 5553333;	return function() {processArtifact(artifactID++);	}}And then we found closure…
Structure and behavior separatedBehavior can change independent of structureAvoids spaghetti codeEvent handling not performed inlineUnobtrusive Javascript
StartAssume javascript not availableImplement acceptable functionalityEndLayer javascript goodness on topImplement javascript-enhanced functionalityDegrade gracefully when javascript cannot be usedProgressive Enhancement
jQuery uses CSS-style selectorsCreates wrapped sets when passed to jQueryjQuery(‘tr:nth-child(2)’)Alias: $(‘tr:nth-child(2)’)Class selectors slower than ID selectorsWhat’s with these selectors?
p > a [all anchor tags, direct children of p tags]div.items a [all anchor tags, descendents of div tags with class of items]div.items:has(a) [all div tags with a class of items that contain anchor tags]a[href^=‘http://’] [all anchor tags, href attribute starts with http://]div#coolness.gunit [all div tags with the id of coolness and class of gunit]Selectors: Child, Container, Attribute
table#itemListtr:even[all even rows in the table with an ID of itemList]:checkbox:checked:enabled[all enabled and checked checkboxes]:enabled:visible[all enabled and visible elements]Selectors: Filters
Function Context: a friendly chameleonThe magical ‘this’
In wrapper methods, set to the current element
Within functions, ‘this’ => function context of the invocationx.desc = ‘x’; y.desc = ‘y’;x.show = function() { alert(this.desc); }x.show(); [outputs ‘x’]x.show.call(y); [outputs ‘y’]
var counter = 1;$(window).bind('click contextmenu', function() {$('#demo').css('font-size', '40')	.append('<div>Timestamp: ' + new Date() + ', counter	= ' + counter + '</div>');	counter++;});Selectors and Closures Demo
Methods on wrapped setssize() => # of elements contained withinfirst(), last() => first or last element withintoArray() => array of DOM elementsnot(exp), filter(exp) => copy of original minus expexp = selector, function, element, or arrayslice(begin, end) => subset within the indiceseach(iterator) => invokes iterator for every elementend() => back up to previous wrapped setandSelf() => merges two previous wrapped sets to anotherManipulating wrapped sets
Browsers implement events differentlyEvent object creation differsEvent propagation differsEvent handler location differsIn other words, it’s great fun!Browser Event Models
Handlers defined inlineLimit: One handler per eventelem.onclick = function(event) { … }Event bubbles up through the DOMReturn false to cancel event propagation	<form onsubmit=“return false;” …Basic Event Model
DOM Level 2 Event ModelAllows multiple event handlers per eventaddEventListener('click', function(event) { ... }, useCapture)useCapture = true => handle capture phase (top to target) event useCapture = false => handle bubble phase (target to top) eventNot supported by IE!IE event model uses legacy event names (onclick vs. click)In IE event model, event instance not passed to handler (use window.event)Newer, Fancier Event Model
Works on all browsersAllows multiple event handlers per eventUses standard event namesEvent instance passed as parameter to handlerLike Level 2 model but no capture phaseLots of ways to attach handlers to eventsjQuery Event Model
Multiple Event Handlers Demo
Event Bubbling Demo
Fun With Event Handlers
Hijacking form postsUse Ajax POST requestsUsed in ASP.NET Update PaneljQuery makes it super simpleEncourages progressive enhancementThe wonderful world of Hijaxing
$('form').submit(function(event) {event.preventDefault();	$.ajaxSetup({	type: 'POST',	timeout: 10000,dataType: 'html'	});	$.ajax({url: 'http://localhost/Demo/Information.asmx/GetInfo',	…	success: function(response) { $('#info').html(response) }	});});Hijaxing: Code Sample
jQuery.event.special.eventNameSpecial Events have these optional methods:setupExecutes when first event handler is bound to elementteardownExecutes when last event handler is bound to elementaddExecutes when each event handler is added to elementremoveExecutes when each event handler is removed from element_default (not that interesting)Executes after event has bubbled to “document”Executes for custom events fired by “trigger” method The Wonders Of Special Events
Setup event handlersCalculate width and heightElement positionAncestryProgenyContainmentFilter and EachMerge and ExtendQuick Rundown of jQueryConfusicons
bind() attaches handler to all elements in wrapped setbind() allows binding multiple events with a handlerlive() attaches handler to current and FUTURE elements via DOM Scriptinglive() binds only one eventlive() can only be invoked on the ORIGINAL wrapped set$('#item', 'tr').closest('table').live('click', function() { ... });delegate() attaches handlers for current and FUTURE elementsdelegate() allows filtering to bind to a subset of wrapped set$('#item').delegate('a', 'click', function() { ... });Binding Event Handlers
css('width') and css('height') return stringse.g. '200px‘width() and height() return integerswidth() and height() can return dimensions of window and documentcss('width') and css('height') throw errors for abovecss('width') and css('height') not always reliableIE returns ‘auto’ for computed dimensionsWidth And Height
position() calculates the offset from nearest ancestor with relative positioningIf none found, defaults to documentoffset() ALWAYS calculates the offset from documentElement Position
parent(selector) returns the immediate parent if it matches the selectorparents(selector) returns all ancestors that match the selectorclosest(selector) returns the closest ancestor that matches the selectorAncestry
children(selector) returns immediate children that match the selectorfind(selector) returns all descendants that match the selectorProgeny
not(selector) returns filtered elements that do not match the selectoris(selector) returns true if any element in the wrapped set matches the selector$('p:not(.info)') SAME AS $('p').not(‘.info’)$(‘table:has(tr)’) returns all tables with at least one rowContainment
filter(selector) returns wrapped set of elements that match the selectorfilter(function) returns wrapped set of all elements for which the function returns trueeach(function) executes the function over all elements in the wrapped set$.each(function) runs on any array like objectfunction context set to the current element being processedFilter and Each
$.merge() combines 2 arrays and saves result to first array$.extend() combines 2+ objects and saves result to first objectjQuery.extend([recursive?], target, object1, ... )Common idiom to use $.extend() to provide default valuesfunction(options) {var settings = $.extend({ prop1: 200, prop2: null,	},	options || {} );}Merge And Extend
Simply assign a function to a property on jQuery ($)Good Idea: Namespacing$.kCura = {};$.kCura.somethingWonderful = function(awesomeness) {	…};Bad Idea: Assume $ has not been appropriated(function($) {	// awesome code goes here}) (jQuery);Extending jQuery: Utility Functions

Javascript And J Query

  • 1.
    Presented by ArsalanAhmedjQuery Goodness – part 1
  • 2.
    Different species thanPOCOsProperties added dynamically upon first useA typo creates a new property – yikes!Properties accessed via: Dot notation (Object.Property)Subscript notation (Object[‘Property’])Literal syntax:varsomeObj = { someProp: ‘some value’, otherProp: 2 };Variables are properties. Equivalent statements in the global scope:var prop = ‘x’; window.prop = ‘x’; prop = x;Objects in Javascript
  • 3.
    Functions are alsoobjectsFunctions can contain other functions!have properties!be assigned to a propertybe passed to a method and also returned from itSmoke and mirrors. Equivalent statements:function someFunc(someParam) { return ‘wow!’ }someFunc = function(someParam) { return ‘wow!’ }window. someFunc = function(someParam) { return ‘wow!’ }So what’s the deal with these functions?
  • 4.
    Local variables stickaroundGreat way to avoid using global variablesAvoids potential naming conflictsExample:var f = function() {varartifactID = 5553333; return function() {processArtifact(artifactID++); }}And then we found closure…
  • 5.
    Structure and behaviorseparatedBehavior can change independent of structureAvoids spaghetti codeEvent handling not performed inlineUnobtrusive Javascript
  • 6.
    StartAssume javascript notavailableImplement acceptable functionalityEndLayer javascript goodness on topImplement javascript-enhanced functionalityDegrade gracefully when javascript cannot be usedProgressive Enhancement
  • 7.
    jQuery uses CSS-styleselectorsCreates wrapped sets when passed to jQueryjQuery(‘tr:nth-child(2)’)Alias: $(‘tr:nth-child(2)’)Class selectors slower than ID selectorsWhat’s with these selectors?
  • 8.
    p > a[all anchor tags, direct children of p tags]div.items a [all anchor tags, descendents of div tags with class of items]div.items:has(a) [all div tags with a class of items that contain anchor tags]a[href^=‘http://’] [all anchor tags, href attribute starts with http://]div#coolness.gunit [all div tags with the id of coolness and class of gunit]Selectors: Child, Container, Attribute
  • 9.
    table#itemListtr:even[all even rowsin the table with an ID of itemList]:checkbox:checked:enabled[all enabled and checked checkboxes]:enabled:visible[all enabled and visible elements]Selectors: Filters
  • 10.
    Function Context: afriendly chameleonThe magical ‘this’
  • 11.
    In wrapper methods,set to the current element
  • 12.
    Within functions, ‘this’=> function context of the invocationx.desc = ‘x’; y.desc = ‘y’;x.show = function() { alert(this.desc); }x.show(); [outputs ‘x’]x.show.call(y); [outputs ‘y’]
  • 13.
    var counter =1;$(window).bind('click contextmenu', function() {$('#demo').css('font-size', '40') .append('<div>Timestamp: ' + new Date() + ', counter = ' + counter + '</div>'); counter++;});Selectors and Closures Demo
  • 14.
    Methods on wrappedsetssize() => # of elements contained withinfirst(), last() => first or last element withintoArray() => array of DOM elementsnot(exp), filter(exp) => copy of original minus expexp = selector, function, element, or arrayslice(begin, end) => subset within the indiceseach(iterator) => invokes iterator for every elementend() => back up to previous wrapped setandSelf() => merges two previous wrapped sets to anotherManipulating wrapped sets
  • 15.
    Browsers implement eventsdifferentlyEvent object creation differsEvent propagation differsEvent handler location differsIn other words, it’s great fun!Browser Event Models
  • 16.
    Handlers defined inlineLimit:One handler per eventelem.onclick = function(event) { … }Event bubbles up through the DOMReturn false to cancel event propagation <form onsubmit=“return false;” …Basic Event Model
  • 17.
    DOM Level 2Event ModelAllows multiple event handlers per eventaddEventListener('click', function(event) { ... }, useCapture)useCapture = true => handle capture phase (top to target) event useCapture = false => handle bubble phase (target to top) eventNot supported by IE!IE event model uses legacy event names (onclick vs. click)In IE event model, event instance not passed to handler (use window.event)Newer, Fancier Event Model
  • 18.
    Works on allbrowsersAllows multiple event handlers per eventUses standard event namesEvent instance passed as parameter to handlerLike Level 2 model but no capture phaseLots of ways to attach handlers to eventsjQuery Event Model
  • 19.
  • 20.
  • 21.
  • 22.
    Hijacking form postsUseAjax POST requestsUsed in ASP.NET Update PaneljQuery makes it super simpleEncourages progressive enhancementThe wonderful world of Hijaxing
  • 23.
    $('form').submit(function(event) {event.preventDefault(); $.ajaxSetup({ type: 'POST', timeout:10000,dataType: 'html' }); $.ajax({url: 'http://localhost/Demo/Information.asmx/GetInfo', … success: function(response) { $('#info').html(response) } });});Hijaxing: Code Sample
  • 24.
    jQuery.event.special.eventNameSpecial Events havethese optional methods:setupExecutes when first event handler is bound to elementteardownExecutes when last event handler is bound to elementaddExecutes when each event handler is added to elementremoveExecutes when each event handler is removed from element_default (not that interesting)Executes after event has bubbled to “document”Executes for custom events fired by “trigger” method The Wonders Of Special Events
  • 25.
    Setup event handlersCalculatewidth and heightElement positionAncestryProgenyContainmentFilter and EachMerge and ExtendQuick Rundown of jQueryConfusicons
  • 26.
    bind() attaches handlerto all elements in wrapped setbind() allows binding multiple events with a handlerlive() attaches handler to current and FUTURE elements via DOM Scriptinglive() binds only one eventlive() can only be invoked on the ORIGINAL wrapped set$('#item', 'tr').closest('table').live('click', function() { ... });delegate() attaches handlers for current and FUTURE elementsdelegate() allows filtering to bind to a subset of wrapped set$('#item').delegate('a', 'click', function() { ... });Binding Event Handlers
  • 27.
    css('width') and css('height')return stringse.g. '200px‘width() and height() return integerswidth() and height() can return dimensions of window and documentcss('width') and css('height') throw errors for abovecss('width') and css('height') not always reliableIE returns ‘auto’ for computed dimensionsWidth And Height
  • 28.
    position() calculates theoffset from nearest ancestor with relative positioningIf none found, defaults to documentoffset() ALWAYS calculates the offset from documentElement Position
  • 29.
    parent(selector) returns theimmediate parent if it matches the selectorparents(selector) returns all ancestors that match the selectorclosest(selector) returns the closest ancestor that matches the selectorAncestry
  • 30.
    children(selector) returns immediatechildren that match the selectorfind(selector) returns all descendants that match the selectorProgeny
  • 31.
    not(selector) returns filteredelements that do not match the selectoris(selector) returns true if any element in the wrapped set matches the selector$('p:not(.info)') SAME AS $('p').not(‘.info’)$(‘table:has(tr)’) returns all tables with at least one rowContainment
  • 32.
    filter(selector) returns wrappedset of elements that match the selectorfilter(function) returns wrapped set of all elements for which the function returns trueeach(function) executes the function over all elements in the wrapped set$.each(function) runs on any array like objectfunction context set to the current element being processedFilter and Each
  • 33.
    $.merge() combines 2arrays and saves result to first array$.extend() combines 2+ objects and saves result to first objectjQuery.extend([recursive?], target, object1, ... )Common idiom to use $.extend() to provide default valuesfunction(options) {var settings = $.extend({ prop1: 200, prop2: null, }, options || {} );}Merge And Extend
  • 34.
    Simply assign afunction to a property on jQuery ($)Good Idea: Namespacing$.kCura = {};$.kCura.somethingWonderful = function(awesomeness) { …};Bad Idea: Assume $ has not been appropriated(function($) { // awesome code goes here}) (jQuery);Extending jQuery: Utility Functions
  • 35.
    Create a propertyon the fn object of jQueryFunction context within main body refers to wrapped setUse each() to work on elements individuallyIf iterating via functions, above iteration automatic$.fn.kCurafy = function() {this.each(function() { makeAwesome($(this).data(‘identifier’)); } function makeAwesome(id) { … }};Usage Example: $(‘img’).kCurafy();Extending jQuery: Wrapper Functions
  • 36.