jquery Source Learning 3--Tools Method Chapter

Source: Internet
Author: User

The basic tools method structure is as follows:

jquery.extend ({init:function() {}, each:function() {}, classname:{add:function() {}, remove:function() {}, has:function() {},}, swap:function() {}, CSS:function() {}, Curcss:function() {}, Clean:function() {}, expr:{}, token:[], find:function() {}, GetAll:function() {}, attr:function() {}, parse:[], filter:function() {}, Trim:function() {}, parents:function() {}, sibling:function() {}, Merge:function() {}, grep:function() {}, Map:function() {}, event:{add:function() {}, GUID:1, global:{}, remove:function() {}, Trigger:function() {}, handle:function() {}, FIX:function(){},    },});

1, Init is essentially extending the instance method, and so on after analyzing the basic tool method, then analysis here

2, each map grep is a set of basic methods, the functions of the three methods are similar, the map also called the merge method, so we will study the merge in a moment, and then back to see each map grep how to achieve

3, classname is relatively independent, is the processing of HTML elements of class, is the inside of the regular is a little bit of trouble

4. The swap method is useful in CSS and curcss, and these methods work together with CSS styles.

5, there are 3 places to use the clean the first jquery constructor inside Dommanip inside Wrap, clean method parameter shape such as <div></div> <a></a> < Table></table>

6, expr and token and parse are a JSON, two arrays, as if it were related to selectors, besides the find and getall and filter, these things are quite complicated

7, Trim method with a very classic regular/^\s+|\s+$/, later version on the basis of optimization, this really nothing to say

8, parents and sibling are methods related to DOM operations

Why did you choose to start with the basic tools approach? Because these methods are the lowest-level JavaScript, no additional top-tier methods are called, instead, take a look at where these methods are invoked to clarify what the execution context is, what the parameters are, and so on.

(1), each

function (obj, FN, args) {    if (obj.length = = undefined        )forvarin  obj)            | | [I, Obj[i]]);     Else         for var i = 0; i < obj.length; i++ )            | | [I, Obj[i]]);     return obj;};

Usually when calling the $.each method, the last parameter, args, is not passed by default, for example

    var arr=[4,5,6,7];    $.each (arr,function(i,v) {        //I is the index of the array, V is the subscript of the array    });

Because an array is passed in, obj has the length property, which means that it will go to the Else branch

Else inside the incoming array is traversed through a normal for loop

Each element in the array executes our incoming callback function, respectively.

It is also possible to see that the first argument is an I that increments each time in a for loop

The second argument is the value of the array entry corresponding to the subscript

The same is true when you pass in a JSON object.

Also, when you call FN, you change the execution environment by using apply, which means that the point of this is forcibly modified to the item that is looped each time.

It is important to note that whether an array is passed in or a JSON

If the value of each item is a basic type, the callback does not change the original array or object.

If the value of each item inside is an object type, the callback will add or remove members to the original array or JSON

(2), grep

 grep: function   (Elems, FN, inv) { if   (Fn.constructor == String) fn  = new                     Function ("A", "I", "return" + FN);  var  result = []; 

for (var i = 0; i < Elems . length; I++) if (!inv && fn (elems[i ],i) | | INV &&! fn (Elems[i],i)) Result.push (Elems[i]); return result; }

If you do not contact the jquery source code, usually work is not a chance to meet the new Function () packaging objects such things

Just checked the information to know its usage: new Function ("param1", "param2" ..., "body")

That is, the last one is the function body, the preceding are all arguments, and all of these are string types

Grep typically uses the following:

    var arr=[1,2,3,4,5,6,7,8];     var filterarr=$.grep (arr,function(v,i) {// filter arr array in terms of function inside        if (v%2) {            returntrue;   return True} if the condition is met    );    Console.log (Filterarr); // [1,3,5,7]

In fact, we usually do the development of the time and the above such a bad usage is good

The second parameter is passed in as a string and then initialized by wrapping the object. Fn is internal to the jquery to simplify operations

This feature is used in many of the following methods.

(3), merge

Mergefunction(first, second) {varresult = []; //Put all the items in first in the result         for(vark = 0; K < First.length; k++) Result[k]=First[k]; //when you put the item inside the second in the result, determine if there is an item in first, and if not, put         for(vari = 0; i < second.length; i++ ) {            varNocollision =true;  for(varj = 0; J < First.length; J + + )                if(Second[i] = =First[j]) nocollision=false; if(nocollision) Result.push (Second[i]); }            returnresult; },

(4), map

Mapfunction(Elems, fn) {if(Fn.constructor = =String) FN=NewFunction ("A", "return" +FN); varresult = [];  for(vari = 0; i < elems.length; i++ ) {            varval =fn (elems[i],i); if(Val!==NULL&& val! =undefined) {                if(Val.constructor! = Array) val =[Val]; Result=Jquery.merge (result, Val); }        }        returnresult; },

The case in which the incoming FN string is processed by the function wrapper object

Like grep, it's also a form of jquery internal invocation.

Regardless of the incoming form, after this FN processing

Determine if the return value is not a meaningful value (if it is null or undefined will be removed)

And then determine if the return value is an array, and if it is an array, merge directly

If it is not an array, create a new array object val

Only one element is stored inside, which is just the result of processing

And then all merge into the result array.

Eventually returns the result array

(5), ClassName

className: {add:function(o,c) {if(JQuery.className.has (O,C))return; O.classname+ = (o.classname?) " " : "" ) +C; }, remove:function(o,c) {o.classname=!c? "": O.classname.replace (NewRegExp ("(^|\\s*\\b[^-)") "+c+" ($|\\b (? =[^-)) "," G ")," ""); }, has:function(e,a) {if(E.classname! =undefined) e=E.classname; return NewRegExp ("(^|\\s)" + A + "(\\s|$)"). Test (e); }    },

First look has, there are two parameters, the meaning is actually very obvious

is to determine if the element e has a class

At first, I understood that by e.classname!=undefined, I had to judge whether the class attribute was added to element E.

But after testing, it was found that whether written

< Div ></ Div >

Or is it written

<class= "abc"></div>

E.classname!=undefined all return True

Because even if there is no class, as long as E is a DOM object, E.classname will return the string

It just returns an empty string without class, and it returns the corresponding class by adding class.

So I guess this place is supposed to be a case where the E is the JS object.

For example: $.classname.has ({"A": 1}, "abc");

This method is called although in New RegExp ("(^|\\s)" + A + "(\\s|$)"). Test (e) The type of the parameter in this regular that does not conform to the method test

But after testing, there is no error, it is estimated that the e.tostring () method is called.

By analyzing the new RegExp ("(^|\\s)" + A + "(\\s|$)") the regular learns

The regular match is the case where Class A is at the beginning or the end, or there are spaces on both sides of a.

This is the approximate logic of have.

Next look at add is very simple, first through the has method to determine the element o There is no C this class

If you do not add it again, return directly

If not, see if this element has the attribute of adding class.

If not, assign C to class directly, and if so, append c after the class attribute value.

Last Look at remove

Because I never had a special demerit. Operator Precedence

So that every time I see someone else's code, it's a live search.

This is no exception, when you first look at the code of the Remove

Thought it was the first execution o.classname =!c

The value of O.classname =!c is then used as the judging condition to perform the following three-mesh

and then we searched the Internet to find out. Assignment operators have the lowest priority

Therefore, this code is the first to determine the value of Class C passed in

The more normal method of transmission is $.classname.remove (ODIV, "abc");

That is, delete the ABC class on ODIV

Then it must have come to me.

O.classname.replace (new RegExp ("(^|\\s*\\b[^-)") "+c+" ($|\\b (? =[^-)) "," G ")," "");

Next analyze the Regular:

In fact, the match within the regular does not necessarily have to match a particular character or string of strings

It can also be a match to a location, such as the \b in this regular case.

This regular principal restricts the front and rear ends of a class from being "-" or starting with this class or ending with this class

jquery Source Learning 3--Tools Method Chapter

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.