JavaScript ToolPak: Cloudgamer JavaScript Library v0.1 released

Source: Internet
Author: User
Tags new set

Research for more than a year JS, also almost write a own JS library.
I write this does not calculate the framework, is just a small JS tool library, so I use the name of the library.
The main collection of I write JS when some of the commonly used methods, and refer to the Prototype.js,jquery,google, Baidu, ah and other frameworks.

The main features of this tool library are:

"Cross-browser"
Can be used in the following browsers: Ie6,ie7,ie8,firefox 3.5.3,chrome 3.0,safari 4.0.3,opera 10.10
IE series is necessary, others can support the latest version is enough.

"Using namespaces"
Of course not really "namespaces", just some global variables, use similar.
The following namespaces are available:
$$: Represent object, Save object related method, also replace the most common getElementById method;
$ $B: Represents browser, saves browser information;
$ $A: Represents an array, preserving the methods associated with arrays and arrays of classes;
$ $F: A method for representing function and preserving functions;
$ $D: Related operations and methods for DOM, document objects;
$ $E: Represents the relevant operation and compatible handling of the Event,dom event;
$ $CE: Represents customevent, custom events for program objects;
$ $S: Represents a string that holds the associated method for the strings.
Although I am not opposed to the moderation of the expansion of native objects, but can also avoid naming pollution.
Using more than one namespace (rather than a single) is easy to use because of ease of administration.
With two $, not to be more American knives (though very much), but to avoid conflicts with the popular framework.
I did not use the window.x form when I used all the variables, because that would lead to some problems, as specific reference here.

"Using Anonymous Functions"
What seems to be jquery is the code embedded in a function.
In fact, the use of closures, one can use local variables, and secondly, can prevent naming conflicts.

"Using Object Detection"
"Object detection is inherently better than browser detection", from the "PPK Talk JavaScript" truth.
can be used to detect the use of objects as far as possible, of course, some are too difficult to engage and not too persistent.
Object detection aspects of jquery's support do well, suggest to look.


The pursuit of goals is:

"Small Size"
The volume here is not about how many characters, but the number of attributes and methods.
The properties and methods of the tool library must be useful, preferably "have to be added".
Of course, with the increase in use, the tool library will gradually expand, but adhere to this principle.

Efficient
Efficiency is the constant pursuit, of course, after the pros and cons.
Speaking of efficiency has to admire Google, it is not only the code to pursue efficiency, and download the code has been detected by the browser.
In particular, you can use each browser to download and try it out.


The purpose of establishment is to:

"Consolidation of common methods"
Combining common methods is beneficial to both code reuse and maintenance.
However, it is inevitable to add some irrelevant methods, which increases the amount of code and reduces the efficiency.

"Resolving compatibility issues"
Solve some common compatibility problems and reduce the burden of coding.


Description of each section

"Object"

The namespace is: $$

$$ itself is the most common method: document.getElementById
It also includes the following methods: Extend, deepextend, and wrapper.
Where extend is the same as the object.extend of Prototype.js, which is one of the longest methods used to extend the object.
And Deepextend is a depth extension, where the depth is similar to the meaning of the deep copy, referring to the extend of jquery.

Emptyfunction preserves an empty function, which is primarily used to conserve resources in place of empty function.

Wrapper complex, mainly used to do inheritance, the main reference has AH $extends (and prototype class.create similar).
Wrapper is a simplified version of $extends that retains only a few key parts:

Code


The difference from traditional archetype inheritance is that an empty function is used as the initialization program to prevent the inheritance of non-prototype property methods.


"Browser"

The namespace is: $ $B

Get browser information through useragent, primarily to get the type and version of the browser.
Here is the basic reference has AH browser, to understand this part of the first to know the browser useragent.
Here are the useragent for each browser (the latest version of the IE series and other browsers):
Ie6
mozilla/4.0 (compatible; MSIE 6.0; ...)
Ie7
mozilla/4.0 (compatible; MSIE 7.0; ...)
Ie8
mozilla/4.0 (compatible; MSIE 8.0; ...)
Ff
mozilla/5.0 (...) gecko/20090824 firefox/3.5.3
Chrome
mozilla/5.0 (...) applewebkit/532.0 (khtml, like Gecko) chrome/3.0.195.27 safari/532.0
Safari
mozilla/5.0 (...) applewebkit/531.9 (khtml, like Gecko) version/4.0.3 safari/531.9.1
Opera
opera/9.80 (...) presto/2.2.15 version/10.10

Determine the browser type by judging the unique characters:

var B = {
MSIE:/msie/.test (UA) &&!/opera/.test (UA),
Opera:/opera/.test (UA),
Safari:/webkit/.test (UA) &&!/chrome/.test (UA),
Firefox:/firefox/.test (UA),
Chrome:/chrome/.test (UA)
};


Get version information is more troublesome, there is Ah browser method is more ingenious (have modified):

var vmark = "";
for (var i in B) {
if (B[i]) {Vmark = "safari" = = I? "Version": I; Break }
}
B.version = Vmark && RegExp ("(?:" + Vmark + ") [\\/:] ([\\d.] +). Test (UA)? Regexp.$1: "0";

But referring to the above useragent will find that opera's acquisition should also use "version" is right, the problem is it before the 10 useragent is this:
opera/9.99 (...) presto/9.9.9
"Version" is not used, in order to apply most of the situation or not to use "version" good, and this judgment is not used much.


"Array"

The namespace is: $ $A

The following methods are included: IsArray, ForEach, map, filter, every, some, indexOf, lastIndexOf
The above method, in addition to IsArray, is a method of adding arrays in JavaScript 1.6.

Where IsArray is used to determine whether an object is an array, indexof and LastIndexOf are element positioning methods, and several others are iterative methods.
These iterative methods can be applied not only to arrays, but also to arrays of classes, such as nodelist,arguments objects, which can also be applied to general objects.

Here I refer to the Jsenhance.js array extension section of the AI, which integrates the same structure in several custom iterative methods.
First, define a basic iteration function each:

Code

When there is a length property (an array or an array of classes), the properties of the object are for...in through the index iterations.
Since the "elements that is deleted is not visited" is specified in the description of the method, use if (I in object) to determine.
It is important to note that when callback returns false, it jumps out of the loop, and with the return value of callback, it is possible to indirectly control the outside jump within the callback.

Then prepare your custom iteration method:

Code

The iteration section is for each to do, here as long as the control of the specific operation of the callback can be.
The closure is used here so that callback can modify the return value of the iteration method.
Every and some use the return value of callback to jump out of the loop.

Once you have defined these methods, use each of these methods again and add them to the namespace:

Code

When the method executes, it first determines whether the object itself has a specified method, and then uses the custom iteration method.


"Function"

The namespace is: $ $F

There are now only two methods: Bind and Bindaseventlistener.
These two are the classic methods inside the Prototype.js, which are used to bind this to the function.
The principle is to use call/apply to change the object of the calling method:

var args = Slice.call (arguments, 2);
return function () {
Return fun.apply (Thisp, Args.concat (slice.call (arguments)));
}

Which used to Array.prototype.slice the arguments object to the group, do not know who found, know this usage on the line.
PS: More than slice, other like concat,join can also be used this way.

Bindaseventlistener Unlike bind, the first parameter is set to the event object, which is specifically used in the events callback function:

var args = Slice.call (arguments, 2);
return function (event) {
Return fun.apply (Thisp, [E.fixevent (event)].concat (args));
}

It uses fixevent to handle event compatibility, which is explained in detail later in the event section.


"Dom"

The namespace is: $ $D

This section is the largest, most complex and most important part of the tool library.
The main thing is to store some DOM operations and solve general compatibility issues.

Getscrolltop and Getscrollleft, respectively, are scrolltop and scrollleft for obtaining document scrolling.
In general, if it should be obtained in standard mode with documentelement, otherwise it will be obtained with body.
But Chrome and Safari (all with the WebKit rendering engine) use the body even in standard mode.
Here's how it's used:

var doc = node? Node.ownerDocument:document;
return Doc.documentElement.scrollTop | | Doc.body.scrollTop;


Priority to get documentelement of the re-select body, so that the basic can be solved.
But this is actually not perfect, if you add the following style to the document:

body{height:300px;overflow:scroll;width:500px;}

The IE6/7 will find that the body section in standard mode is rendered at the specified height and width, and can have a scrollbar.
This means that documentelement and body can set scrolltop.
That time to get which is not clear, fortunately, the general situation does not need to set this (at least I have not touched).
For such a special case, it is OK to know the situation, there is no need to add too much code for it.
PS: The obtained scrollleft/scrollleft is not negative.

The Contains method is to determine whether the parameter 1 element object contains a parameter 2 element object.
The main use of IE contains and the comparedocumentposition to judge.
Refer to the Compare Document Locations section here.

There are two element coordinate-related methods: Rect and Clientrect.
Where rect is relative to the location of the browser document, Clientrect is relative to the location of the browser window.
When Getboundingclientrect is supported, it is used with getscrollleft/getscrolltop to get the document location.
Otherwise, it is obtained by looping the offsetleft/offsettop of the offsetparent.
Refer to the Comparison element location section here.

There are also three style-related methods: CurStyle, GetStyle, SetStyle
CurStyle is used to get the final stylesheet of an element, returning getComputedStyle or Currentstyle (IE) based on support.
PS: Here is a priority to judge getComputedStyle, because opera also supports Currentstyle.

GetStyle is used to get the final style value of the element's specified style property.
Support getComputedStyle directly with it to get the style of computed value on the line, about computed value can refer to here.
While Currentstyle is a bit like getComputedStyle to get the final style, the two get the same form of value.
Unlike getComputedStyle, it returns the exact uniform value of the specification after rendering, but only a set value.
And this value is not necessarily the exact value after rendering.
The main thing of the program is to try to get close to getComputedStyle value in IE.

The first is to deal with the transparency, ie, although using a filter but its value divided by 100 is the same as the "opacity" value:

if (/alpha\ (opacity= (. *) \)/i.test (Style.filter)) {
var opacity = parsefloat (regexp.$1);
return opacity? opacity/100:0;
}
return 1;

There is also "float", this relatively simple replaced by "stylefloat" on the line.

One more work after getting the style is the conversion unit. The conversion occurs when the value being judged is a value and the unit is not PX.
The method is to refer to the curcss of jquery, before understanding the two less useful attributes: Runtimestyle and Pixelleft.

Runtimestyle is a unique attribute of IE, it uses the same style, but it has the highest priority.
This means that if you set the style in Runtimestyle, you will ignore the same style in the style.
Refer to Birdshome's "about the differences between three style instances in HTML Object" and "about using Runtimestyle attribute issues"
The function of Pixelleft is to return the element's left style value in pixels px, ie (also used in Runtimestyle) and opera support.

Knowing these two things, you can understand how it works:
1, first back up the original value:

style = Elem.style, left = style.left, rsleft = Elem.runtimeStyle.left;

2, set the left of Runtimestyle to Currentstyle left:

Elem.runtimeStyle.left = Elem.currentStyle.left;

The purpose is to make use of the priority of Runtimestyle to ensure that the style can be displayed according to the original pattern.
3, set the left of the style to the value to be converted, and skillfully use Pixelleft to get the PX unit form of this value:

Style.left = RET | | 0;
RET = style.pixelleft + "px";

4, finally restore the original left value:

Style.left = left;
Elem.runtimeStyle.left = Rsleft;

This allows you to convert to pixel values without changing the rendering style.
Ps:jquery that this method is also proposed by Dean Edwards, God.

Finally, there is a setstyle used to set the style, mainly for batch styling and to solve some compatibility problems.
Calls can be made in the following two ways:
$ $D. SetStyle (element or element collection, {Style Property name: Property value, ...})
$ $D. SetStyle (element or element collection, style attribute name, property value)
The first parameter is the element or collection of elements to set the style, and if it is a single element it automatically turns into a single-element collection:

if (!elems.length) {elems = [elems];}


The second parameter is a set of key-value pairs, the key is the style property name, and the value is the corresponding property value.
If you set only one style, you can set the second parameter to be the style property name, the third parameter is the property value, and the program creates a new set of key-value pairs:

if (typeof style = = "string") {var s = style; style = {}; style[s] = value;}


Then use the foreach calendar to set all the elements in the binding function to give the elements a list of all the styles used in.
PS: single element setting a single style should be set directly, unless there is a compatibility issue.

The rest is to solve the compatibility problem.
First of all, the transparency, IE is the filter, if the direct setting filter will replace the other filters are not.
Refer to the JQuery method, first get the original filter, replace the transparent filter portion, plus the transparent filter to be set:

Elem.style.filter = (Elem.currentStyle.filter | | ""). Replace (/alpha\ ([^)]*\)/, "") +
"Alpha (opacity=" + value * 100 + ")";


Very ingenious method, remember the value is multiplied by 100 corresponding to the "opacity".

As for "float" is relatively simple, ie with "stylefloat" other use "cssfloat" on the line.


"Event"

The namespace is: $ $E

This is an old compatibility problem, and here are three ways to do it: addevent,removeevent,fixevent.

Addevent and Removeevent respectively is to add and remove events, I used to use IE attachevent with the AddEventListener do compatible.
But after seeing Dean Edwards's method, he switched to his, and in addition to the compatibility of a better solution to some of the bugs (see the CloneNode in this section of the bug).
The addevent/removeevent in the code made some changes based on the Dean Code, but the principle was the same.
Also compatible with "MouseEnter" and "MouseLeave" events.

And fixevent is used to correct the compatibility of the event object, mainly to add some of the properties and methods of the Bindaseventlistener, which used it.
Here I only do the compatibility of IE, the other is directly using the event, so do not be meticulous compatibility, but enough on the line.
The fix on jquery is perfect and worth studying.


"Customevent"

The namespace is: $ $CE

The above event can only be used on DOM events, but programs sometimes require some "custom" events.
Customevent is the custom event that is used in the program.

This is mostly modeled after the event, including Addevent and Removeevent, and a fireevent method for manually triggering events.
Its main purpose is to add hooks to the program and to add multiple programs at the same time.


"String"

The namespace is: $ $S

I'm less of a high-level application for string, so there's no way to put it in for the moment.
There is a camelize method that converts a string in the form of a bar (such as "Border-top") into a hump form (for example, "BorderTop").
The principle is to use the second parameter of replace as a function technique:

Return S.replace (/-([A-z])/ig, function (all, letter) {return letter.touppercase ();});

This conversion can be used in the name of the style attribute, which is used in Getstyle/setstyle.


Invocation mode

Finally, the calling method is the same as calling the general function method, but with the namespace in front of me.
Example: $$.extend (...)
Like $$ because itself is function, you can use it directly: $$ (...)
Chained calls may be cool, but not very suitable for use in such a library, unless it is an extended native object (not used here).

Version download
Cloudgamer JavaScript Library v0.1
Full version compressed version

JavaScript ToolPak: Cloudgamer JavaScript Library v0.1 released

Related Article

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.