jQuery Data Manipulate<br />A source code dissecting journey<br />Dean Yan <br />http://thefronts.com/<br /> http://deanya...
HTML5 data-* Attributes<br /><li class="user" data-name="John Resig" data-city="Boston"data-lang="js" data-food="Bacon">  ...
HTML5 data-* Attributes<br />The .dataset property behaves very similarly to the the .attributes property (but it only wor...
HTML5 data-* Attributes<br />“<br />While I firmly believe that useful data should be made visible to users, there are cir...
HTML5 data-* Attributes<br />Taking a step back, we can use data-* attributes on the body element to provide an indication...
.data()/jQuery.data()<br />.data( key, value )<br />.data( key, value ) <br />.data( obj ) <br />.data( key )<br />.data( ...
.data()/jQuery.data()<br /><div>    The values stored were     <span></span>    and    <span></span></div><br />$("div").d...
.data()/jQuery.data()<br />var myObj = {};$(myObj).data("city", "Springfield");<br />myObj.city = "Springfield"<br />var p...
.data()/jQuery.data()<br />getData – triggered before data is read from the object.<br />changeData – triggered whenever d...
. removeData()/ jQuery.removeData()<br />.removeData( [ name ] )<br /><div>value1 before creation: <span></span></div><div...
jQuery.hasData()<br />jQuery.hasData( element )<br />“<br />The primary advantage of jQuery.hasData(element) is that it do...
jQuery.hasData()<br />$(function(){  var $p = jQuery("p"), p = $p[0];<br />  $p.append(jQuery.hasData(p)+" "); /* false */...
Utilities<br />jQuery.isFunction()<br />jQuery.globalEval()<br />jQuery.isEmptyObject()<br />jQuery.merge()<br />jQuery.pr...
Utilities<br />jQuery.isFunction()<br />// Populate the class2type mapjQuery.each("Boolean Number String Function Array Da...
Utilities<br />jQuery.trim()<br />// Use native String.trim function wherever possibletrim: trim ?function(text) {    retu...
Utilities<br />jQuery.isEmptyObject()<br />isEmptyObject: function(obj) {    for (var name in obj) {        return false; ...
Utilities<br />jQuery.isPlainObject()<br />isPlainObject: function(obj) {    // Must be an Object.    // Because of IE, we...
Utilities<br />jQuery.globalEval()<br />globalEval: function(data) {    if (data && rnotwhite.test(data)) {        // We u...
Utilities<br />jQuery.proxy()<br />// Bind a function to a context, optionally partially applying any// arguments.proxy: f...
Utilities<br />jQuery.each()<br />// args is for internal usage onlyeach: function(object, callback, args) {    var name, ...
Utilities<br />jQuery.each()<br />      // A special, fast, case for the most common use of each    } else {        if (is...
Miscellaneous<br />.index() <br />.map()<br />.get()<br />.toArray()<br />.slice()<br />
Miscellaneous<br />.index()<br />.index( selector )<br />selector A selector representing a jQuery collection in which to ...
Miscellaneous<br />.index()<br />On click, returns the index (based zero) of that div in the page.<br /><span>Click a div!...
Miscellaneous<br />.index()<br />Returns the index for the element with ID bar in relation to all <li> elements.<br /><ul>...
Miscellaneous<br />toArray()<br />toArray: function() {    return slice.call(this, 0);}<br />Reversed - <span></span><div>...
Miscellaneous<br />.map()<br />.map( callback(index, domElement) )<br />callback(index, domElement)A function object that ...
Miscellaneous<br />.map()<br />Equalize the heights of the divs.<br /><input type="button" value="equalize div heights"><d...
Miscellaneous<br />.map()<br />map: function(callback) {    return this.pushStack(jQuery.map(this, function(elem, i) {    ...
Miscellaneous<br />.map()<br />// arg is for internal usage onlymap: function(elems, callback, arg) {    var value, key, r...
Miscellaneous<br />.map()<br />// Take an array of elements and push it onto the stack// (returning the new matched elemen...
Miscellaneous<br />.index()<br />// Determine the position of an element within// the matched set of elementsindex: functi...
Miscellaneous<br />.get()<br />// Get the Nth element in the matched element set OR// Get the whole matched element set as...
General Attributes<br />.attr()<br />.removeAttr()<br />.prop()<br />.removeProp()<br />
General Attributes<br />.attr()	.removeAttr()<br />attr: function(name, value) {    return jQuery.access(this, name, value...
General Attributes<br />.prop()	.removeProp()<br />prop: function(name, value) {    return jQuery.access(this, name, value...
Upcoming SlideShare
Loading in …5
×

jQuery Data Manipulate API - A source code dissecting journey

1,959 views

Published on

Represent major data manipulate API in jQuery 1.6; such as .data(), removeData(), index(), globalEval() and so no. Also, HTML5 data-* attributes. I will walk you through with diving into jQuery source code and find out the killing techniques used in jQuery.

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

  • Be the first to like this

No Downloads
Views
Total views
1,959
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
20
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

jQuery Data Manipulate API - A source code dissecting journey

  1. 1. jQuery Data Manipulate<br />A source code dissecting journey<br />Dean Yan <br />http://thefronts.com/<br /> http://deanyan.com/<br />http://www.linkedin.com/in/deanyan/<br />
  2. 2. HTML5 data-* Attributes<br /><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><br />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);<br />REF> http://ejohn.org/blog/html-5-data-attributes/<br />
  3. 3. HTML5 data-* Attributes<br />The .dataset property behaves very similarly to the the .attributes property (but it only works as a map of key-value pairs) <br />span.innerHTML = phrase.prefix +  user.getAttribute("data-" + phrase.name )<br />
  4. 4. HTML5 data-* Attributes<br />“<br />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:<br />”<br /><span<br />data-lat="38.8951" <br />data-lng="-77.0363"><br />    1600 Pennsylvania Ave.    Washington, DC<br /></span><br />REF> http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/<br />
  5. 5. HTML5 data-* Attributes<br />Taking a step back, we can use data-* attributes on the body element to provide an indication of where we are within an application:<br /><body data-controller="<%= controller_name %>" data-action="<%= action_name %>"><br />The above code will yield something like:<br /> <body data-controller="users" data-action="show"><br />REF> http://www.viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution/<br />
  6. 6. .data()/jQuery.data()<br />.data( key, value )<br />.data( key, value ) <br />.data( obj ) <br />.data( key )<br />.data( key ) <br />.data() <br />
  7. 7. .data()/jQuery.data()<br /><div>    The values stored were     <span></span>    and    <span></span></div><br />$("div").data("test", { first: 16, last: "pizza!" });$("span:first").text($("div").data("test").first);$("span:last").text($("div").data("test").last);<br /><div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div><br />$("div").data("role") === "page";$("div").data("lastValue") === 43;$("div").data("hidden") === true;$("div").data("options").name === "John";<br />
  8. 8. .data()/jQuery.data()<br />var myObj = {};$(myObj).data("city", "Springfield");<br />myObj.city = "Springfield"<br />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<br />
  9. 9. .data()/jQuery.data()<br />getData – triggered before data is read from the object.<br />changeData – triggered whenever data is set or changed. It is used in the jQuery datalinkplugin .<br />
  10. 10. . removeData()/ jQuery.removeData()<br />.removeData( [ name ] )<br /><div>value1 before creation: <span></span></div><div>value1 after creation: <span></span></div><div>value1 after removal: <span></span></div><br />$("span:eq(0)").text("" + $("div").data("test1"));<br />$("div").data("test1", "VALUE-1");$("div").data("test2", "VALUE-2");<br />$("span:eq(1)").text("" + $("div").data("test1"));$("div").removeData("test1");<br />$("span:eq(2)").text("" + $("div").data("test1"));$("span:eq(3)").text("" + $("div").data("test2"));<br />
  11. 11. jQuery.hasData()<br />jQuery.hasData( element )<br />“<br />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. <br />”<br />
  12. 12. jQuery.hasData()<br />$(function(){  var $p = jQuery("p"), p = $p[0];<br />  $p.append(jQuery.hasData(p)+" "); /* false */  jQuery.data(p, "testing", 123);<br />  $p.append(jQuery.hasData(p)+" "); /* true*/  jQuery.removeData(p, "testing");<br />  $p.append(jQuery.hasData(p)+" "); /* false */});<br />
  13. 13. Utilities<br />jQuery.isFunction()<br />jQuery.globalEval()<br />jQuery.isEmptyObject()<br />jQuery.merge()<br />jQuery.proxy()<br />jQuery.each()<br />jQuery.trim()<br />jQuery.extend()<br />
  14. 14. Utilities<br />jQuery.isFunction()<br />// Populate the class2type mapjQuery.each("Boolean Number String Function Array Date RegExpObject".split(" "), function(i, name) {    class2type["[object " + name + "]"] =name.toLowerCase();});<br />type: function(obj) {    return obj == null ? String(obj) :class2type[toString.call(obj)] || "object";},<br />// 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";},<br />
  15. 15. Utilities<br />jQuery.trim()<br />// Use native String.trim function wherever possibletrim: trim ?function(text) {    return text == null ? "" : trim.call(text);} :// Otherwise use our own trimming functionalityfunction(text) {    return text == null ? "" :text.toString().replace(trimLeft,"")<br /> .replace(trimRight, "");},<br />
  16. 16. Utilities<br />jQuery.isEmptyObject()<br />isEmptyObject: function(obj) {    for (var name in obj) {        return false;    }    return true;},<br />
  17. 17. Utilities<br />jQuery.isPlainObject()<br />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") <br /> &&!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);},<br />
  18. 18. Utilities<br />jQuery.globalEval()<br />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);    }},<br />
  19. 19. Utilities<br />jQuery.proxy()<br />// 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;},<br />
  20. 20. Utilities<br />jQuery.each()<br />// args is for internal usage onlyeach: 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;                }            }        }<br />
  21. 21. Utilities<br />jQuery.each()<br />      // 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++]) === false) {                    break;                }            }        }    }    return object;},<br />
  22. 22. Miscellaneous<br />.index() <br />.map()<br />.get()<br />.toArray()<br />.slice()<br />
  23. 23. Miscellaneous<br />.index()<br />.index( selector )<br />selector A selector representing a jQuery collection in which to look for an element.<br />.index( element )<br />element The DOM element or first element within the jQuery object to look for.<br />
  24. 24. Miscellaneous<br />.index()<br />On click, returns the index (based zero) of that div in the page.<br /><span>Click a div!</span><div>First div</div><div>Second div</div><div>Third div</div><script>    <br /> $("div").click(function () {        // this is the dom element clicked<br />        var index = $("div").index(this);        $("span").text("That was div index #" + index);<br />    });</script><br />
  25. 25. Miscellaneous<br />.index()<br />Returns the index for the element with ID bar in relation to all <li> elements.<br /><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><br />
  26. 26. Miscellaneous<br />toArray()<br />toArray: function() {    return slice.call(this, 0);}<br />Reversed - <span></span><div>One</div><div>Two</div><div>Three</div><script><br />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><br />
  27. 27. Miscellaneous<br />.map()<br />.map( callback(index, domElement) )<br />callback(index, domElement)A function object that will be invoked for each element in the current set.<br />
  28. 28. Miscellaneous<br />.map()<br />Equalize the heights of the divs.<br /><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(){<br />     return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height() }).get() ) )    }<br />    $('input').click(function(){     $('div').equalizeHeights();    });</script><br />
  29. 29. Miscellaneous<br />.map()<br />map: function(callback) {    return this.pushStack(jQuery.map(this, function(elem, i) {        return callback.call(elem, i, elem);    }));},<br />
  30. 30. Miscellaneous<br />.map()<br />// arg is for internal usage onlymap: 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);},<br />
  31. 31. Miscellaneous<br />.map()<br />// 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;},<br />
  32. 32. Miscellaneous<br />.index()<br />// Determine the position of an element within// the matched set of elementsindex: 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);},<br />
  33. 33. Miscellaneous<br />.get()<br />// Get the Nth element in the matched element set OR// Get the whole matched element set as a clean arrayget: function(num) {    return num == null ?    // Return a 'clean' array    this.toArray() :    // Return just the object    (num < 0 ? this[this.length + num] : this[num]);},<br />
  34. 34. General Attributes<br />.attr()<br />.removeAttr()<br />.prop()<br />.removeProp()<br />
  35. 35. General Attributes<br />.attr() .removeAttr()<br />attr: function(name, value) {    return jQuery.access(this, name, value, true, jQuery.attr);},<br />removeAttr: function(name) {    return this.each(function() {        jQuery.removeAttr(this, name);    });},<br />
  36. 36. General Attributes<br />.prop() .removeProp()<br />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) {}    });},<br />

×