Setter/getter Mode for JQuery 3.0

Source: Internet
Author: User
<span id="Label3"></p><p><p>JQuery's Setter/getter share a function that shows what it means by passing a parameter. Simply speaking, it is a setter, not a getter.</p></p><p><p>A function with many meanings is not uncommon in programming languages, such as <strong>function overloading</strong> : A set of functions with the same function name and different parameter lists, which are called overloaded Functions. The advantage of overloading is that it reduces the number of function names, avoids the pollution of namespaces, and helps the readability of the Program.</p></p><p><p>function overloading mainly embodies the two aspects, one is the type of parameters, the same number of parameter types can be called function overloading, the second is the number of parameters, the number of different is also called function overloading. Note that overloading is not related to the return value of a Function.</p></p><p><p>Because of the characteristics of JS weak type, to simulate function overloading can only be achieved by the second way: the number of Parameters. therefore, the arguments object within the function is very important.</p></p><p><p></p></p><p><p>The following is an example</p></p><pre class="brush:javascript;gutter:true;"><pre class="brush:javascript;gutter:true;">function Doadd () {var argslength = Arguments.lengthif (argslength = = = 0) {return 0} else if (argslength = = 1) {return arg uments[0] + ten} else if (argslength = = = 2) {return arguments[0] + arguments[1]}}doadd () //0doAdd (5)//15doAdd (5, 20) 25</pre></pre><p><p>Doadd three meanings by judging the number of parameters of the function, argslength is 0 o'clock, returns 0 directly, argslength is 1 o'clock, The parameter is added to 10, and Argslength is added to the 2 o'clock two Parameters.</p></p><p><p><br>Using the function overloading feature can realize setter/getter</p></p><pre class="brush:javascript;gutter:true;"><pre class="brush:javascript;gutter:true;">function text () {var elem = This.elemvar Argslength = Arguments.lengthif (argslength = = 0) {return elem.innertext} Else I F (argslength = = = 1) {elem.innertext = arguments[0]}}</pre></pre><p><p></p></p><p><p>The above simply explains the function overloading and uses it to implement Setter/getter. That is, the "accessor" and the "evaluator". Whether it is a value or an assignment is determined by the parameters of the Function. Many of JQuery's API designs Use this pattern extensively.</p></p><p><p>Summarizes all the APIs in JQuery that use this pattern, a total of 14 functions</p></p><p><p></p></p><p><p></p></p><p><p>All of these functions rely on another function, access, which is no exaggeration to say that access is the core of all these functions, is the core of implementing Setter/getter. Here is the source code of this function, it is a private function, external is not called it.</p></p><p><p></p></p><p><p></p></p><p><p>The source code for access is as follows</p></p><pre class="brush:javascript;collapse:true;;gutter:true;">Multifunctional method to get and set values of a collection//the value/s can optionally be executed if it ' s a functio Nvar access = function (elems, fn, key, value, chainable, emptyget, raw) {var i = 0,len = Elems.length,bulk = key = = NULL ;//sets many valuesif (jquery.type (key) = = = "object") {chainable = true;for (i in Key) {access (elems, fn, i, key[ i], true, emptyget, raw);} Sets one value} else if (value!== undefined) {chainable = true;if (!jquery.isfunction (value)) {raw = true;} If (BULK) {//bulk operations run against the entire setif (raw) {fn.call (elems, value); fn = null;//... except when Executing function values} Else {bulk = FN;FN = function (elem, key, value) {return bulk.call (jQuery (elem), value);} ;}} If (fn) {for (; i < len; i++) {fn (elems[i], key, raw value:value.call (elems[i], i, fn (elems[i], key)); }}}return chainable elems://getsbulk? fn.call (elems): len? fn (elems[0], key): emptyget;};</pre><p><p>  </p></p><p><p>The comment for this function refers to: this is a multifunctional function that gets and sets the attributes and values of a collection Element. Value can be an executable function. This function has less than 60 lines of Code. Reading from the top, the first if is to set multiple value values, which is a recursive call. By planing This recursive call, the code for setting a single value is less than 50 lines. Write very concise, Read-resistant.</p></p><p><p></p></p><p><p>To understand the access function, I drew two graphs</p></p><p><p></p></p><p><p>Two main branches within access</p></p><p><p></p></p><p><p></p></p><p><p>The execution process inside access</p></p><p><p></p></p><p><p></p></p><p><p>Access defines a formal parameter that has 7</p></p> <ol> <ol> <li><strong>elems</strong> Element collection, the actual call to simultaneous is this, here is the jquery object, we know that the jquery object itself is a collection, with the length property and Index. Must pass.</li> <li>the <strong>fn</strong> implements the Setter/getter function, which means that the function needs to have the condition to determine which part is the setter and which part is the Getter. Must pass.</li> <li><strong>key</strong> such as attr and prop methods to pass, set or get the value of which key. Some do not have to pass, but for the placeholder for null substitution, such as text, HTML method. Optional.</li> <li><strong>value</strong> is passed only when the setter is undefined, which is the getter when value is a, or setter. Optional.</li> <li><strong>chainable</strong> When true, the JQuery object is returned when the setter mode is Entered. False to enter Getter Mode. Pass through Arguments.length or arguments.length>1 when it is Invoked.</li> <li><strong>Emptyget</strong> When the JQuery object is empty, The result returned is null, which is not passed by default to the Undefined,data method call Simultaneous.</li> <li><strong>Raw</strong> When value is a function type, raw is false, otherwise True.</li> </ol> </ol><p><p></p></p><p><p>As mentioned above, access is the core of all JQuery Setter/getter functions, in other words, access is called inside all 14 functions Setter/getter Functions. That's Why Access has 7 parameters, many of which are branches. Because it has to deal with a lot of conditions. But all of these setter/getter have a lot of code that is similar, and finally extract a common Function.</p></p><p><p></p></p><p><p>For the sake of understanding, I categorized the call of access below to make it easier for us to understand.</p></p><p><p></p></p><p><p>1. When you call access, the third parameter key has a value of null, which is the Text/html method</p></p><pre class="brush:javascript;collapse:true;;gutter:true;">Text:function (value) {return access (this, function (value) {return value = = = undefined? Jquery.text (this): this.emp Ty (). each (function () {if (this.nodetype = = = 1 | | this.nodetype = = = | | this.nodetype = = 9) {this.textcontent = value ;}} );}, null, value, arguments.length);},html:function (value) {return access (this, function (value) {var elem = this[0 ] || {},i = 0,l = this.length;if (value = = = Undefined && Elem.nodetype = = 1) {return elem.innerhtml;} See if we can take a shortcut and just use innerhtmlif (typeof value = = = "string" &&!rnoinnerhtml.test (value ) &&!wrapmap[(rtagname.exec (value) | | [ "", "" ] ) [1].tolowercase ()]) {value = jquery.htmlprefilter (value); try {for (; i < l; i++) {elem = this[i] | | {};//Remove element nodes and prevent memory leaksif (elem.nodetype = = 1) {jquery.cleandata (getAll (elem, false)); E lem.innerhtml = value;}} Elem = 0;//If using InnerHTML throws an exception, use the fallback method} catch (e) {}}if (elem) {this.empty (). append (value);}}, null, value, arguments.length);}, </pre><p><p></p></p><p><p>The two methods are shown in the internal access execution</p></p><p><p></p></p><p><p></p></p><p><p>Why does key pass NULL because the DOM API is already provided. The text method is set or fetched using el.innertext, and the HTML method is set or obtained using InnerHTML (in this case, there are actually some exception handling).</p></p><p><p></p></p><p><p>2. In contrast to the first case, when you call access, the key value is passed and is not Null. It's the same with all the other setters except Text/html.</p></p><pre class="brush:javascript;collapse:true;;gutter:true;">Attr:function (name, value) {return access (this, jquery.attr, name, value, arguments.length > 1);},prop:function ( name, Value) {return Access (this, jquery.prop, name, value, arguments.length > 1);},//Create scrollleft and Scrollt Op methodsjquery.each ({scrollleft: "pagexoffset", scrolltop: "pageyoffset"}, function (method, prop) {var top = "pagey Offset "= = = prop;jquery.fn[method] = function (val) {return access (this, function (elem, method, val) {var win = GETW Indow (elem), if (val = = = Undefined) {return win win[prop]: elem[method];} If (win) {win.scrollto (!top. val:win.pagexoffset,top? val:win.pageYOffset);} Else {elem[method] = val;}, method , val, arguments.length);};} ); css:function (name, value) {return access (this, function (elem, name, value) {var styles, len,map = {},i = 0;if (jQ Uery.isarray (name)) {styles = getstyles (elem); len = name.length;for (; i < len; i++) {map[name[i]] = jQuery. CSS (elem, name[i], false, styles);} Return map;} return value!== undefined? jquery.style (elem, name, value): jquery.css (elem, name);}, name, value, Arguments.length & Gt 1);} Create innerheight, innerwidth, height, width, outerheight and outerwidth methodsjquery.each ({height: "height", width : "width"}, function (name, Type) {jquery.each ({padding: "inner" + name, content:type, "": "outer" + name},function ( defaultextra, FuncName) {//margin is only for outerheight, outerwidthjquery.fn[funcName] = function (margin, Value) {var chainable = arguments.length && (defaultextra | | typeof margin!== "boolean"), extra = Defaultextra | | (margin = = True | | value = = true?) "margin": "border"); return access (this, function (elem, type, value) {var doc;if (jquery.iswindow (elem)) {//$ (wi Ndow). outerwidth/height return w/h including scrollbars (gh-1729) return funcname.indexof ("outer") = = = 0? elem["inner" + name]: elem.document.documentelement["client" + name];} Get Document Width or HEightif (elem.nodetype = = 9) {doc = Elem.documentelement;//either scroll[width/height] or offset[width/height] or Clie Nt[width/height],//whichever is Greatestreturn math.max (elem.body["scroll" + name], doc["scroll" + name],elem.body[" Offset "+ name", doc["offset" + name],doc["client" + name]);} return value = = = Undefined?//Get width or height on the element, requesting but not forcing PARSEFLOATJQUERY.CSS (elem, type, extra)://Set width or height on the elementjquery.style (elem, type, value, extra);}, type, chainable? margin:undefined, chainable);};} );} );d ata:function (key, value) {var i, name, data,elem = this[0],attrs = Elem && elem.attributes;//Gets all Val Uesif (key = = = Undefined) {if (this.length) {data = Datauser.get (elem); if (elem.nodetype = = = 1 &&!datapriv . Get (elem, "hasdataattrs")) {i = attrs.length;while (i--) {//support:ie One only//the attrs elements can be null (# 14894) if (attrs[i]) {name = attrs[i].name;If (name.indexof ("data-") = = = 0) {name = jquery.camelcase (name.slice (5));d ataattr (elem, name, data[name]);}}} Datapriv.set (elem, "hasdataattrs", true);}} Return data;} Sets multiple valuesif (typeof key = = = "object") {return this.each (function () {datauser.set (this, key);}); Return access (this, function (value) {var data;//the calling JQuery object (element matches) was not empty//(and theref Ore has a element appears at This[0]) and the//' value ' parameter is not undefined. An empty jQuery object//would result in ' undefined ' for elem = this[0] which will//throw an exception if a attempt to Read a data cache is Made.if (elem && value = = = Undefined) {//attempt to get data from the Cache//the key would Always being camelcased in datadata = Datauser.get (elem, key); if (data!== undefined) {return data;} Attempt to "discover" the data in//HTML5 custom data-* attrsdata = dataattr (elem, key); if (data!== undefined) {re Turn data;} We tried realLy hard, But the data doesn ' t exist.return;} Set the Data...this.each (function () {//We always store the camelcased keydatauser.set (this, key, value);});}, null , value, arguments.length > 1, null, true);},</pre><p><p></p></p><p><p>Figure out how these methods are performed inside access</p></p><p><p></p></p><p><p></p></p><p><p>Not finished:</p></p><p><p></p></p><p><p>Setter/getter Mode for JQuery 3.0</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.