SlideShare a Scribd company logo
Presented by Arsalan Ahmed jQuery Goodness – part 1
Different species than POCOs Properties added dynamically upon first use A 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 objects Functions can  contain other functions! have properties! be assigned to a property be passed to a method and also returned from it Smoke 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 around Great way to avoid using global variables Avoids potential naming conflicts Example: var f = function() { varartifactID = 5553333; 	return function() { processArtifact(artifactID++); 	} } And then we found closure…
Structure and behavior separated Behavior can change independent of structure Avoids spaghetti code Event handling not performed inline Unobtrusive Javascript
Start Assume javascript not available Implement acceptable functionality End Layer javascript goodness on top Implement javascript-enhanced functionality Degrade gracefully when javascript cannot be used Progressive Enhancement
jQuery uses CSS-style selectors Creates wrapped sets when passed to jQuery jQuery(‘tr:nth-child(2)’) Alias: $(‘tr:nth-child(2)’) Class selectors slower than ID selectors What’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 chameleon ,[object Object]
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 sets size() => # of elements contained within first(), last() => first or last element within toArray() => array of DOM elements not(exp), filter(exp) => copy of original minus exp exp = selector, function, element, or array slice(begin, end) => subset within the indices each(iterator) => invokes iterator for every element end() => back up to previous wrapped set andSelf() => merges two previous wrapped sets to another Manipulating wrapped sets
Browsers implement events differently Event object creation differs Event propagation differs Event handler location differs In other words, it’s great fun! Browser Event Models
Handlers defined inline Limit: One handler per event elem.onclick = function(event) { … } Event bubbles up through the DOM Return false to cancel event propagation 	<form onsubmit=“return false;” … Basic Event Model
DOM Level 2 Event Model Allows multiple event handlers per event addEventListener('click', function(event) { ... }, useCapture) useCapture = true => handle capture phase (top to target) event  useCapture = false => handle bubble phase (target to top) event Not 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 browsers Allows multiple event handlers per event Uses standard event names Event instance passed as parameter to handler Like Level 2 model but no capture phase Lots of ways to attach handlers to events jQuery Event Model
Multiple Event Handlers Demo
Event Bubbling Demo
Fun With Event Handlers
Hijacking form posts Use Ajax POST requests Used in ASP.NET Update Panel jQuery makes it super simple Encourages progressive enhancement The 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.eventName Special Events have these optional methods: setup Executes when first event handler is bound to element teardown Executes when last event handler is bound to element add Executes when each event handler is added to element remove Executes 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 handlers Calculate width and height Element position Ancestry Progeny Containment Filter and Each Merge and Extend Quick Rundown of jQueryConfusicons
bind() attaches handler to all elements in wrapped set bind() allows binding multiple events with a handler live() attaches handler to current and FUTURE elements via DOM Scripting live() binds only one event live() can only be invoked on the ORIGINAL wrapped set $('#item', 'tr').closest('table').live('click', function() { ... }); delegate() attaches handlers for current and FUTURE elements delegate() allows filtering to bind to a subset of wrapped set $('#item').delegate('a', 'click', function() { ... }); Binding Event Handlers
css('width') and css('height') return strings e.g. '200px‘ width() and height() return integers width() and height() can return dimensions of window and document css('width') and css('height') throw errors for above css('width') and css('height') not always reliable IE returns ‘auto’ for computed dimensions Width And Height
position() calculates the offset from nearest ancestor with relative positioning If none found, defaults to document offset() ALWAYS calculates the offset from document Element Position
parent(selector) returns the immediate parent if it matches the selector parents(selector) returns all ancestors that match the selector closest(selector) returns the closest ancestor that matches the selector Ancestry
children(selector) returns immediate children that match the selector find(selector) returns all descendants that match the selector Progeny
not(selector) returns filtered elements that do not match the selector is(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 row Containment
filter(selector) returns wrapped set of elements that match the selector filter(function) returns wrapped set of all elements for which the function returns true each(function) executes the function over all elements in the wrapped set $.each(function) runs on any array like object function context set to the current element being processed Filter and Each
$.merge() combines 2 arrays and saves result to first array $.extend() combines 2+ objects and saves result to first object jQuery.extend([recursive?], target, object1, ... ) Common idiom to use $.extend() to provide default values function(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

More Related Content

What's hot

jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
Stijn Van Minnebruggen
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Thomas Fuchs
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Enrique Juan de Dios
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
Henrik Engström
 
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014
Matthias Noback
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
KrisKowal2
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
Naresh Kumar
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
WebStackAcademy
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
jeresig
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Troy Miles
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
Juriy Zaytsev
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 

What's hot (20)

jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014
 
Hardened JavaScript
Hardened JavaScriptHardened JavaScript
Hardened JavaScript
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
 
jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 

Similar to Javascript And J Query

jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Divakar Gu
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
saydin_soft
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
J Query
J QueryJ Query
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
Pradeep Saraswathi
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
JavaScript
JavaScriptJavaScript
JavaScript
Bharti Gupta
 
J query training
J query trainingJ query training
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
Bastian Feder
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
jQuery
jQueryjQuery
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experiment
wgamboa
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
Marco Otte-Witte
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
rsnarayanan
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
johndaviddalton
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
Nerd Tzanetopoulos
 
Closure
ClosureClosure
Closure
Xiaojun REN
 

Similar to Javascript And J Query (20)

jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
J Query
J QueryJ Query
J Query
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
JavaScript
JavaScriptJavaScript
JavaScript
 
J query training
J query trainingJ query training
J query training
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
jQuery
jQueryjQuery
jQuery
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experiment
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Closure
ClosureClosure
Closure
 

Javascript And J Query

  • 1. Presented by Arsalan Ahmed jQuery Goodness – part 1
  • 2. Different species than POCOs Properties added dynamically upon first use A 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 also objects Functions can contain other functions! have properties! be assigned to a property be passed to a method and also returned from it Smoke 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 stick around Great way to avoid using global variables Avoids potential naming conflicts Example: var f = function() { varartifactID = 5553333; return function() { processArtifact(artifactID++); } } And then we found closure…
  • 5. Structure and behavior separated Behavior can change independent of structure Avoids spaghetti code Event handling not performed inline Unobtrusive Javascript
  • 6. Start Assume javascript not available Implement acceptable functionality End Layer javascript goodness on top Implement javascript-enhanced functionality Degrade gracefully when javascript cannot be used Progressive Enhancement
  • 7. jQuery uses CSS-style selectors Creates wrapped sets when passed to jQuery jQuery(‘tr:nth-child(2)’) Alias: $(‘tr:nth-child(2)’) Class selectors slower than ID selectors What’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 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
  • 10.
  • 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 wrapped sets size() => # of elements contained within first(), last() => first or last element within toArray() => array of DOM elements not(exp), filter(exp) => copy of original minus exp exp = selector, function, element, or array slice(begin, end) => subset within the indices each(iterator) => invokes iterator for every element end() => back up to previous wrapped set andSelf() => merges two previous wrapped sets to another Manipulating wrapped sets
  • 15. Browsers implement events differently Event object creation differs Event propagation differs Event handler location differs In other words, it’s great fun! Browser Event Models
  • 16. Handlers defined inline Limit: One handler per event elem.onclick = function(event) { … } Event bubbles up through the DOM Return false to cancel event propagation <form onsubmit=“return false;” … Basic Event Model
  • 17. DOM Level 2 Event Model Allows multiple event handlers per event addEventListener('click', function(event) { ... }, useCapture) useCapture = true => handle capture phase (top to target) event useCapture = false => handle bubble phase (target to top) event Not 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 all browsers Allows multiple event handlers per event Uses standard event names Event instance passed as parameter to handler Like Level 2 model but no capture phase Lots of ways to attach handlers to events jQuery Event Model
  • 21. Fun With Event Handlers
  • 22. Hijacking form posts Use Ajax POST requests Used in ASP.NET Update Panel jQuery makes it super simple Encourages progressive enhancement The 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.eventName Special Events have these optional methods: setup Executes when first event handler is bound to element teardown Executes when last event handler is bound to element add Executes when each event handler is added to element remove Executes 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 handlers Calculate width and height Element position Ancestry Progeny Containment Filter and Each Merge and Extend Quick Rundown of jQueryConfusicons
  • 26. bind() attaches handler to all elements in wrapped set bind() allows binding multiple events with a handler live() attaches handler to current and FUTURE elements via DOM Scripting live() binds only one event live() can only be invoked on the ORIGINAL wrapped set $('#item', 'tr').closest('table').live('click', function() { ... }); delegate() attaches handlers for current and FUTURE elements delegate() 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 strings e.g. '200px‘ width() and height() return integers width() and height() can return dimensions of window and document css('width') and css('height') throw errors for above css('width') and css('height') not always reliable IE returns ‘auto’ for computed dimensions Width And Height
  • 28. position() calculates the offset from nearest ancestor with relative positioning If none found, defaults to document offset() ALWAYS calculates the offset from document Element Position
  • 29. parent(selector) returns the immediate parent if it matches the selector parents(selector) returns all ancestors that match the selector closest(selector) returns the closest ancestor that matches the selector Ancestry
  • 30. children(selector) returns immediate children that match the selector find(selector) returns all descendants that match the selector Progeny
  • 31. not(selector) returns filtered elements that do not match the selector is(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 row Containment
  • 32. filter(selector) returns wrapped set of elements that match the selector filter(function) returns wrapped set of all elements for which the function returns true each(function) executes the function over all elements in the wrapped set $.each(function) runs on any array like object function context set to the current element being processed Filter and Each
  • 33. $.merge() combines 2 arrays and saves result to first array $.extend() combines 2+ objects and saves result to first object jQuery.extend([recursive?], target, object1, ... ) Common idiom to use $.extend() to provide default values function(options) { var settings = $.extend({ prop1: 200, prop2: null, }, options || {} ); } Merge And Extend
  • 34. 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
  • 35. Create a property on the fn object of jQuery Function context within main body refers to wrapped set Use each() to work on elements individually If 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