SlideShare a Scribd company logo
jQuery Data Manipulate
A source code dissecting journey
Huiyi Yan
HTML5 data-* Attributes
<li class="user" data-name="John Resig" data-city="Boston"
data-lang="js" data-food="Bacon">
<b>John says:</b> <span>Hello, how are you?</span>
</li>
var user = document.getElementsByTagName("li")[0];
var pos = 0, span = user.getElementsByTagName("span")[0];
var phrases = [
{name: "city", prefix: "I am from "},
{name: "food", prefix: "I like to eat "},
{name: "lang", prefix: "I like to program in "}
];
user.addEventListener( "click", function(){
var phrase = phrases[ pos++ ];
// Use the .dataset property
span.innerHTML = phrase.prefix + user.dataset[ phrase.name ];
}, false);
REF> http://ejohn.org/blog/html-5-data-attributes/
HTML5 data-* Attributes
span.innerHTML = phrase.prefix +
user.getAttribute("data-" + phrase.name )
The .dataset property behaves very similarly to
the the .attributes property (but it only works as
a map of key-value pairs)
HTML5 data-* Attributes
While I firmly believe that useful data should be made visible to users, there are
circumstances where data-* attributes make sense. For instance, including
data-lat and data-lng attributes in an element containing a street address would
allow for easily adding markers to a Google Map on the page:
<span
data-lat="38.8951"
data-lng="-77.0363">
1600 Pennsylvania Ave.
Washington, DC
</span>
“
”
REF> http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
HTML5 data-* Attributes
Taking a step back, we can use data-* attributes on the body element to
provide an indication of where we are within an application:
<body data-controller="<%= controller_name %>" data-
action="<%= action_name %>">
<body data-controller="users" data-action="show">
The above code will yield something like:
REF> http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
.data()/jQuery.data()
.data( key, value )
.data( key, value )
.data( obj )
.data( key )
.data( key )
.data()
.data()/jQuery.data()
<div>
The values stored were
<span></span>
and
<span></span>
</div>
$("div").data("test", { first: 16, last: "pizza!" });
$("span:first").text($("div").data("test").first);
$("span:last").text($("div").data("test").last);
<div data-role="page" data-last-value="43" data-
hidden="true" data-options='{"name":"John"}'></div>
$("div").data("role") === "page";
$("div").data("lastValue") === 43;
$("div").data("hidden") === true;
$("div").data("options").name === "John";
.data()/jQuery.data()
var myObj = {};
$(myObj).data("city", "Springfield");
myObj.city = "Springfield"
var progressBar = {};
$(progressBar).bind('setData', function(e, key, value) {
switch (key) {
case "percent":
$("#progress").width(value + "%");
$("#percentText").text(value + "%");
break;
case "color":
$("#progress").css("color", value);
break;
case "enabled":
$('#progress').toggleClass("active", value);
break;
}
});
$(progressBar).data("enabled", true).data("percent", 21).data("color","green");
// You also have easy access to the current values:
console.log(progressBar.enabled); // true
.data()/jQuery.data()
getData – triggered before data is read from the object.
changeData – triggered whenever data is set or changed. It is used
in the jQuery datalink plugin .
. removeData()/ jQuery.removeData()
.removeData( [ name ] )
<div>value1 before creation: <span></span></div>
<div>value1 after creation: <span></span></div>
<div>value1 after removal: <span></span></div>
$("span:eq(0)").text("" + $("div").data("test1"));
$("div").data("test1", "VALUE-1");
$("div").data("test2", "VALUE-2");
$("span:eq(1)").text("" + $("div").data("test1"));
$("div").removeData("test1");
$("span:eq(2)").text("" + $("div").data("test1"));
$("span:eq(3)").text("" + $("div").data("test2"));
jQuery.hasData()
jQuery.hasData( element )
The primary advantage of jQuery.hasData(element) is
that it does not create and associate a data object with
the element if none currently exists. In contrast,
jQuery.data(element) always returns a data object to the
caller, creating one if no data object previously existed.
“
”
jQuery.hasData()
$(function(){
var $p = jQuery("p"), p = $p[0];
$p.append(jQuery.hasData(p)+" "); /* false */
jQuery.data(p, "testing", 123);
$p.append(jQuery.hasData(p)+" "); /* true*/
jQuery.removeData(p, "testing");
$p.append(jQuery.hasData(p)+" "); /* false */
});
Utilities
jQuery.isEmptyObject()
jQuery.trim()
jQuery.isFunction()
jQuery.each()
jQuery.globalEval()
jQuery.merge()
jQuery.proxy()
jQuery.extend()
Utilities
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp
Object".split(" "), function(i, name) {
class2type["[object " + name + "]"] =name.toLowerCase();
});
type: function(obj) {
return obj == null ? String(obj) :class2type[toString.cal
l(obj)] || "object";
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function(obj) {
return jQuery.type(obj) === "function";
},
jQuery.isFunction()
Utilities
// Use native String.trim function wherever possible
trim: trim ?
function(text) {
return text == null ? "" : trim.call(text);
} :
// Otherwise use our own trimming functionality
function(text) {
return text == null ? "" :text.toString().replace(trimLef
t,"")
.replace(trimRight, "");
},
jQuery.trim()
Utilities
isEmptyObject: function(obj) {
for (var name in obj) {
return false;
}
return true;
},
jQuery.isEmptyObject()
Utilities
isPlainObject: function(obj) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor
property.
// Make sure that DOM nodes and window objects don't pass through, as well
if (!obj || jQuery.type(obj) !== "object" ||obj.nodeType || jQuery.isWindow(obj
)) {
return false;
}
// Not own constructor property must be Object
if (obj.constructor && !hasOwn.call(obj,"constructor")
&&!hasOwn.call(obj.constructor.prototype,"isPrototypeOf")) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) {}
return key === undefined || hasOwn.call(obj,key);
},
jQuery.isPlainObject()
Utilities
globalEval: function(data) {
if (data && rnotwhite.test(data)) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is
window
// rather than jQuery in Firefox
(window.execScript ||
function(data) {
window["eval"].call(window, data);
})(data);
}
},
jQuery.globalEval()
Utilities
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function(fn, context) {
if (typeof context === "string") {
var tmp = fn[context];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if (!jQuery.isFunction(fn)) {
return undefined;
}
// Simulated bind
var args = slice.call(arguments, 2),
proxy = function() {
return fn.apply(context,args.concat(slice.call(arguments)));
};
// Set the guid of unique handler to the same of original handler, so it
can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid ||jQuery.guid++;
return proxy;
},
jQuery.proxy()
UtilitiesjQuery.each()
// args is for internal usage only
each: function(object, callback, args) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if (args) {
if (isObj) {
for (name in object) {
if (callback.apply(object[name], args) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.apply(object[i++], args) === false) {
break;
}
}
}
UtilitiesjQuery.each()
// A special, fast, case for the most common use of each
} else {
if (isObj) {
for (name in object) {
if (callback.call(object[name], name, object[name])
===false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.call(object[i], i, object[i++]) === fa
lse) {
break;
}
}
}
}
return object;
},
Miscellaneous
.index()
.map()
.get()
.toArray()
.slice()
Miscellaneous
.index()
.index( selector )
selector A selector representing a jQuery collection in
which to look for an element.
.index( element )
element The DOM element or first element within the jQuery
object to look for.
Miscellaneous
<span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
<script>
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span").text("That was div index #" + index);
});
</script>
.index()
On click, returns the index (based zero) of that div in the
page.
Miscellaneous
<ul>
<li id="foo">foo</li>
<li id="bar">bar</li>
<li id="baz">baz</li>
</ul>
<div></div>
<script>$('div').html('Index: ' + $('#bar').index('li')
);</script>
.index()
Returns the index for the element with ID bar in relation
to all <li> elements.
Miscellaneous
toArray: function() {
return slice.call(this, 0);
}
Reversed - <span></span>
<div>One</div>
<div>Two</div>
<div>Three</div>
<script>
function disp(divs) {
var a = [];
for (var i = 0; i < divs.length; i++) {
a.push(divs[i].innerHTML);
}
$("span").text(a.join(" "));
}
disp($("div").toArray().reverse());
</script>
toArray()
Miscellaneous
.map(
).map( callback(index, domElement) )
callback(index, domElement)A function object that will be
invoked for each element in the current set.
Miscellaneous
<input type="button" value="equalize div heights">
<div style="background:red; height: 40px; "></div>
<div style="background:green; height: 70px;"></div>
<div style="background:blue; height: 50px; "></div>
<script>
$.fn.equalizeHeights = function(){
return this.height( Math.max.apply(this,
$(this).map(function(i,e){ return $(e).height() }).get() ) )
}
$('input').click(function(){
$('div').equalizeHeights();
});
</script>
.map(
)Equalize the heights of the divs.
Miscellaneous
map: function(callback) {
return this.pushStack(jQuery.map(this, function(
elem, i) {
return callback.call(elem, i, elem);
}));
},
.map(
)
Miscellaneous// arg is for internal usage only
map: function(elems, callback, arg) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined &&typeof length === "number" &
& ((length > 0 && elems[0] && elems[length -1]) || length === 0 || jQuery.isArray(elems));
// Go through the array, translating each of the items to their
if (isArray) {
for (; i < length; i++) {
value = callback(elems[i], i, arg);
if (value != null) {
ret[ret.length] = value;
}
}
// Go through every key on the object,
} else {
for (key in elems) {
value = callback(elems[key], key, arg);
if (value != null) {
ret[ret.length] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply([], ret);
},
.map(
)
Miscellaneous
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function(elems, name, selector) {
// Build a new jQuery matched element set
var ret = this.constructor();
if (jQuery.isArray(elems)) {
push.apply(ret, elems);
} else {
jQuery.merge(ret, elems);
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if (name === "find") {
ret.selector = this.selector + (this.selector ? " " : "") +selector;
} else if (name) {
ret.selector = this.selector + "." + name + "(" + selector +")";
}
// Return the newly-formed element set
return ret;
},
.map(
)
Miscellaneous
// Determine the position of an element within
// the matched set of elements
index: function(elem) {
if (!elem || typeof elem === "string") {
return jQuery.inArray(this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery(elem) : this.parent().children());
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is
used
elem.jquery ? elem[0] : elem, this);
},
.index()
Miscellaneous
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function(num) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
(num < 0 ? this[this.length + num] : this[num]);
},
.get()
General Attributes
.attr()
.removeAttr()
.prop()
.removeProp()
General Attributes
attr: function(name, value) {
return jQuery.access(this, name, value, true, jQuery.a
ttr);
},
removeAttr: function(name) {
return this.each(function() {
jQuery.removeAttr(this, name);
});
},
.attr() .removeAttr()
General Attributes
prop: function(name, value) {
return jQuery.access(this, name, value, true, jQuery.
prop);
},
removeProp: function(name) {
return this.each(function() {
// try/catch handles cases where IE balks (such
as removing a property on window)
try {
this[name] = undefined;
delete this[name];
} catch (e) {}
});
},
.prop() .removeProp()

More Related Content

What's hot

Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
Rebecca Murphey
 
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 2KThomas Fuchs
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
Rebecca Murphey
 
jQuery
jQueryjQuery
jQuery
Jay Poojara
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Gil Fink
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
Remy Sharp
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
Rebecca Murphey
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
Anis Ahmad
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
Diego Fleury
 
Organizing Code with JavascriptMVC
Organizing Code with JavascriptMVCOrganizing Code with JavascriptMVC
Organizing Code with JavascriptMVC
Thomas Reynolds
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j queryMd. Ziaul Haq
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
J query1
J query1J query1
J query1
Manav Prasad
 
J query
J queryJ query
J query
Manav Prasad
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
jeresig
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 

What's hot (20)

Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
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
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
jQuery
jQueryjQuery
jQuery
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
Organizing Code with JavascriptMVC
Organizing Code with JavascriptMVCOrganizing Code with JavascriptMVC
Organizing Code with JavascriptMVC
 
J query training
J query trainingJ query training
J query training
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
J query1
J query1J query1
J query1
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
J query
J queryJ query
J query
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 

Similar to jQuery Data Manipulate API - A source code dissecting journey

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranRobert Nyman
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
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 Secretssmueller_sandsmedia
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
Nick Lee
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowRobert Nyman
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
David Jacobs
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
Tomasz Dziuda
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
johndaviddalton
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloRobert Nyman
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
johndaviddalton
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
kvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
kvangork
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
Constantin Titarenko
 

Similar to jQuery Data Manipulate API - A source code dissecting journey (20)

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
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
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, MoscowJavaScript APIs - The Web is the Platform - .toster conference, Moscow
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 

Recently uploaded

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 

jQuery Data Manipulate API - A source code dissecting journey

  • 1. jQuery Data Manipulate A source code dissecting journey Huiyi Yan
  • 2. HTML5 data-* Attributes <li class="user" data-name="John Resig" data-city="Boston" data-lang="js" data-food="Bacon"> <b>John says:</b> <span>Hello, how are you?</span> </li> var user = document.getElementsByTagName("li")[0]; var pos = 0, span = user.getElementsByTagName("span")[0]; var phrases = [ {name: "city", prefix: "I am from "}, {name: "food", prefix: "I like to eat "}, {name: "lang", prefix: "I like to program in "} ]; user.addEventListener( "click", function(){ var phrase = phrases[ pos++ ]; // Use the .dataset property span.innerHTML = phrase.prefix + user.dataset[ phrase.name ]; }, false); REF> http://ejohn.org/blog/html-5-data-attributes/
  • 3. HTML5 data-* Attributes span.innerHTML = phrase.prefix + user.getAttribute("data-" + phrase.name ) The .dataset property behaves very similarly to the the .attributes property (but it only works as a map of key-value pairs)
  • 4. HTML5 data-* Attributes While I firmly believe that useful data should be made visible to users, there are circumstances where data-* attributes make sense. For instance, including data-lat and data-lng attributes in an element containing a street address would allow for easily adding markers to a Google Map on the page: <span data-lat="38.8951" data-lng="-77.0363"> 1600 Pennsylvania Ave. Washington, DC </span> “ ” REF> http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
  • 5. HTML5 data-* Attributes Taking a step back, we can use data-* attributes on the body element to provide an indication of where we are within an application: <body data-controller="<%= controller_name %>" data- action="<%= action_name %>"> <body data-controller="users" data-action="show"> The above code will yield something like: REF> http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/
  • 6. .data()/jQuery.data() .data( key, value ) .data( key, value ) .data( obj ) .data( key ) .data( key ) .data()
  • 7. .data()/jQuery.data() <div> The values stored were <span></span> and <span></span> </div> $("div").data("test", { first: 16, last: "pizza!" }); $("span:first").text($("div").data("test").first); $("span:last").text($("div").data("test").last); <div data-role="page" data-last-value="43" data- hidden="true" data-options='{"name":"John"}'></div> $("div").data("role") === "page"; $("div").data("lastValue") === 43; $("div").data("hidden") === true; $("div").data("options").name === "John";
  • 8. .data()/jQuery.data() var myObj = {}; $(myObj).data("city", "Springfield"); myObj.city = "Springfield" var progressBar = {}; $(progressBar).bind('setData', function(e, key, value) { switch (key) { case "percent": $("#progress").width(value + "%"); $("#percentText").text(value + "%"); break; case "color": $("#progress").css("color", value); break; case "enabled": $('#progress').toggleClass("active", value); break; } }); $(progressBar).data("enabled", true).data("percent", 21).data("color","green"); // You also have easy access to the current values: console.log(progressBar.enabled); // true
  • 9. .data()/jQuery.data() getData – triggered before data is read from the object. changeData – triggered whenever data is set or changed. It is used in the jQuery datalink plugin .
  • 10. . removeData()/ jQuery.removeData() .removeData( [ name ] ) <div>value1 before creation: <span></span></div> <div>value1 after creation: <span></span></div> <div>value1 after removal: <span></span></div> $("span:eq(0)").text("" + $("div").data("test1")); $("div").data("test1", "VALUE-1"); $("div").data("test2", "VALUE-2"); $("span:eq(1)").text("" + $("div").data("test1")); $("div").removeData("test1"); $("span:eq(2)").text("" + $("div").data("test1")); $("span:eq(3)").text("" + $("div").data("test2"));
  • 11. jQuery.hasData() jQuery.hasData( element ) The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed. “ ”
  • 12. jQuery.hasData() $(function(){ var $p = jQuery("p"), p = $p[0]; $p.append(jQuery.hasData(p)+" "); /* false */ jQuery.data(p, "testing", 123); $p.append(jQuery.hasData(p)+" "); /* true*/ jQuery.removeData(p, "testing"); $p.append(jQuery.hasData(p)+" "); /* false */ });
  • 14. Utilities // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type["[object " + name + "]"] =name.toLowerCase(); }); type: function(obj) { return obj == null ? String(obj) :class2type[toString.cal l(obj)] || "object"; }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function(obj) { return jQuery.type(obj) === "function"; }, jQuery.isFunction()
  • 15. Utilities // Use native String.trim function wherever possible trim: trim ? function(text) { return text == null ? "" : trim.call(text); } : // Otherwise use our own trimming functionality function(text) { return text == null ? "" :text.toString().replace(trimLef t,"") .replace(trimRight, ""); }, jQuery.trim()
  • 16. Utilities isEmptyObject: function(obj) { for (var name in obj) { return false; } return true; }, jQuery.isEmptyObject()
  • 17. Utilities isPlainObject: function(obj) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if (!obj || jQuery.type(obj) !== "object" ||obj.nodeType || jQuery.isWindow(obj )) { return false; } // Not own constructor property must be Object if (obj.constructor && !hasOwn.call(obj,"constructor") &&!hasOwn.call(obj.constructor.prototype,"isPrototypeOf")) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) {} return key === undefined || hasOwn.call(obj,key); }, jQuery.isPlainObject()
  • 18. Utilities globalEval: function(data) { if (data && rnotwhite.test(data)) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox (window.execScript || function(data) { window["eval"].call(window, data); })(data); } }, jQuery.globalEval()
  • 19. Utilities // Bind a function to a context, optionally partially applying any // arguments. proxy: function(fn, context) { if (typeof context === "string") { var tmp = fn[context]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if (!jQuery.isFunction(fn)) { return undefined; } // Simulated bind var args = slice.call(arguments, 2), proxy = function() { return fn.apply(context,args.concat(slice.call(arguments))); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || proxy.guid ||jQuery.guid++; return proxy; }, jQuery.proxy()
  • 20. UtilitiesjQuery.each() // args is for internal usage only each: function(object, callback, args) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if (args) { if (isObj) { for (name in object) { if (callback.apply(object[name], args) === false) { break; } } } else { for (; i < length;) { if (callback.apply(object[i++], args) === false) { break; } } }
  • 21. UtilitiesjQuery.each() // A special, fast, case for the most common use of each } else { if (isObj) { for (name in object) { if (callback.call(object[name], name, object[name]) ===false) { break; } } } else { for (; i < length;) { if (callback.call(object[i], i, object[i++]) === fa lse) { break; } } } } return object; },
  • 23. Miscellaneous .index() .index( selector ) selector A selector representing a jQuery collection in which to look for an element. .index( element ) element The DOM element or first element within the jQuery object to look for.
  • 24. Miscellaneous <span>Click a div!</span> <div>First div</div> <div>Second div</div> <div>Third div</div> <script> $("div").click(function () { // this is the dom element clicked var index = $("div").index(this); $("span").text("That was div index #" + index); }); </script> .index() On click, returns the index (based zero) of that div in the page.
  • 25. Miscellaneous <ul> <li id="foo">foo</li> <li id="bar">bar</li> <li id="baz">baz</li> </ul> <div></div> <script>$('div').html('Index: ' + $('#bar').index('li') );</script> .index() Returns the index for the element with ID bar in relation to all <li> elements.
  • 26. Miscellaneous toArray: function() { return slice.call(this, 0); } Reversed - <span></span> <div>One</div> <div>Two</div> <div>Three</div> <script> function disp(divs) { var a = []; for (var i = 0; i < divs.length; i++) { a.push(divs[i].innerHTML); } $("span").text(a.join(" ")); } disp($("div").toArray().reverse()); </script> toArray()
  • 27. Miscellaneous .map( ).map( callback(index, domElement) ) callback(index, domElement)A function object that will be invoked for each element in the current set.
  • 28. Miscellaneous <input type="button" value="equalize div heights"> <div style="background:red; height: 40px; "></div> <div style="background:green; height: 70px;"></div> <div style="background:blue; height: 50px; "></div> <script> $.fn.equalizeHeights = function(){ return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) ) } $('input').click(function(){ $('div').equalizeHeights(); }); </script> .map( )Equalize the heights of the divs.
  • 29. Miscellaneous map: function(callback) { return this.pushStack(jQuery.map(this, function( elem, i) { return callback.call(elem, i, elem); })); }, .map( )
  • 30. Miscellaneous// arg is for internal usage only map: function(elems, callback, arg) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined &&typeof length === "number" & & ((length > 0 && elems[0] && elems[length -1]) || length === 0 || jQuery.isArray(elems)); // Go through the array, translating each of the items to their if (isArray) { for (; i < length; i++) { value = callback(elems[i], i, arg); if (value != null) { ret[ret.length] = value; } } // Go through every key on the object, } else { for (key in elems) { value = callback(elems[key], key, arg); if (value != null) { ret[ret.length] = value; } } } // Flatten any nested arrays return ret.concat.apply([], ret); }, .map( )
  • 31. Miscellaneous // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function(elems, name, selector) { // Build a new jQuery matched element set var ret = this.constructor(); if (jQuery.isArray(elems)) { push.apply(ret, elems); } else { jQuery.merge(ret, elems); } // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if (name === "find") { ret.selector = this.selector + (this.selector ? " " : "") +selector; } else if (name) { ret.selector = this.selector + "." + name + "(" + selector +")"; } // Return the newly-formed element set return ret; }, .map( )
  • 32. Miscellaneous // Determine the position of an element within // the matched set of elements index: function(elem) { if (!elem || typeof elem === "string") { return jQuery.inArray(this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery(elem) : this.parent().children()); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this); }, .index()
  • 33. Miscellaneous // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function(num) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object (num < 0 ? this[this.length + num] : this[num]); }, .get()
  • 35. General Attributes attr: function(name, value) { return jQuery.access(this, name, value, true, jQuery.a ttr); }, removeAttr: function(name) { return this.each(function() { jQuery.removeAttr(this, name); }); }, .attr() .removeAttr()
  • 36. General Attributes prop: function(name, value) { return jQuery.access(this, name, value, true, jQuery. prop); }, removeProp: function(name) { return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[name] = undefined; delete this[name]; } catch (e) {} }); }, .prop() .removeProp()