Advanced front-end siege lion: Design native JS plugin using monomer mode

Source: Internet
Author: User
Tags jquery library

----------retrofit based on the last written jquery plugin http://www.cnblogs.com/GerryOfZhong/p/5533773.html

background : jquery plugins rely on the jquery library, although jquery is widely used, but for mobile development or other bandwidth needs to be aware of, it has to be considered, because I can not complete a technology relative to reference a larger library, so it is not worthwhile. So native JS is a language supported by all browsers, the original JS is relatively very good, but the native JS relative novice or not very strong foundation of the person is relatively abstruse obscure point, after all, to consider some additional factors:

    • Do not pollute global variables, because you do not know that your code will conflict with other libraries or page-loaded AD code
    • Some high-level design patterns, because some design patterns are very classical ideas of condensation, with language implementation is relatively more complex
    • Front-end object-oriented programming, because JS degrees of freedom is relatively high, not as defined in the background. such as analog interfaces, inheritance, encapsulation, etc., to achieve a powerful architecture or demand
    • ..........

design mode : monomer mode

The advantage: When using the monomer mode, you will enjoy all the benefits of a true private member without paying any price, because the single tear will only be instantiated once monomer mode is one of the most popular and widely used patterns in JavaScript

      • Self-explanatory nature of descriptive naming enhanced code
      • The package monomer can prevent others from being wrongly altered.
      • Isolated from third-party libraries and ads
      • Later optimizations, such as lazy loading

Disadvantages: In the use of monomer mode, you must be very familiar with the concept of closures, and later combined with other design patterns common use, complexity and code is relatively demanding, so users need to measure, value is not worth using, will increase the difficulty of project development. If it's worth it, it's not recommended.

The following is the skeleton of the closure monomer pattern (with empty dedicated design mode and some cases and use):

varNamespance= window.namespance| | {};//Declaring a spaceNamespance.gerry=(function(){    //private properties and private methods can be stored here, not open to the outside, and prevent other developers from changing them privately.    varPrivateattr =false; functionPrivatemethod () {Console.log ("This is private method, not open to the outside ..."); }    //This is a throw object for developers to use.    varPublicobject ={publicattr:true, Publicmethod:function() {Console.log ("This is the throw method for developers to use ...")        }    }    returnPublicobject;}) ()    

Native code design:

  1. Declare space and build a skeleton
    var gerry = Window.gerry | | {};  // declaration gerry.setbackgroundimage = (function() {

    Publicmethods = {};
        Publicmethods
    })()

  2. Set the default value of the plug-in (note: The default value does not provide external modifications, do not open the privileged method to set change its value)
    varGerry = Window.gerry | | {};//StatementGerry.setbackgroundimage = (function(){        //Private parameter setting (not open)         varconfig={imgarr: [],//Image Arrayimgsecond:1000,//the time the picture fades outIsrandom:false    //Is a random picture        }        //the method that exposes the developer to use, can expand freely        varPublicmethods = {}; returnPublicmethods;}) ()

  3. Encapsulate some tool and put it in a private method, because after all it's not jquery, some methods need to be encapsulated
    varTool = {            //ID SelectorId_selector:function(selector) {returndocument.getElementById (selector); },            //Create a nodeCreateElement:function(node) {returndocument.createelement (node); },            //Set node Propertiesattrfunction(setarrobject) { for(vari = 0,len=setarrobject.attribute.length;i<len;i++) {SetArrObject.node.setAttribute (setarrobject.attribute[i].key,setarrobject.attribute[i].value                ); }            }        }

  4. Set some styles that you want to use and put them in a CSS object
            // set the style        var css = {            ' position:absolute;left:0;top:0;z-index:-1;overflow:hidden;width:100%;height : 100% ',            imgt:' position:absolute;left:0;top:0;z-index:-2;opacity:0; ' ,        }

  5. Encapsulate some private methods to deal with some common methods, such as parameter processing AH what
    //private method, not open to the outside        varPrivatemethods = {            //handle the developer's configurationParahandling:function(option) {varconfigtemp; if(Option.config! = undefined) {//the developer sets the valueoption.config.imgarr== undefined? OPTION.CONFIG.IMGARR =config.imgarr:NULL; Option.config.imgSecond= = undefined? Option.config.imgSecond = Config.imgsecond:NULL; Option.config.isRandom= = undefined? Option.config.isRandom = Config.israndom:NULL; Configtemp=Option.config; }Else{configtemp=config;                }; returnconfigtemp; },            //process fade-out effect for IE9 because IE9 does not support transitionDivfadein:function(option) {if(Option.selector = =undefined) {                    Throw NewError ("Please select a ID (div)."))                }Else{                    varShowTime =Number (Option.config.imgSecond); varOpacityvalue = 0;//set the property value of opacity                    varDivselector = Tool.id_selector (option.selector);//get the div ID                    vartemp = SetInterval (function() {Opacityvalue+=0.01; DivSelector.style.opacity=Opacityvalue; if(opacityvalue>1) {clearinterval (temp); }},showtime/100); For IE9 with opacity with setinterval timing function to achieve fade-out effect, pay attention to control the frequency of the refresh, give visual a smooth feeling                }            },            //Create a content themeCreatecontent:function(option) {//Set ID                vardivimg = tool.createelement ("div"); varObject_div ={node:divimg, attribute:[{ Key:"id", Value:"Divshow"}, {key:"Style", Value:css.divT}]                };                Tool.attr (OBJECT_DIV); //Setting the IMG property                varimg = tool.createelement ("img"); varObject_div ={node:img, attribute:[{key :"id", Value:"Imgshow"}, {key:"Style", Value:css. IMGT+ "Transition:opacity" +option.config.imgsecond/1000+ "s Ease",                        }                    ]                };                Tool.attr (OBJECT_DIV);                Divimg.appendchild (IMG);                Document.body.appendChild (DIVIMG); Privatemethods.delayloadimg (option.config.imgarr[0]); },            //Delay Loading PicturesDELAYLOADIMG:function(IMG_SRC) {varIMG =NewImage (); IMG.SRC=img_src; Img.onload=function(){                    vartemp ={node:tool.id_selector ("Imgshow"), attribute:[{key:"SRC", VALUE:IMG_SRC}]                    };                    Tool.attr (temp); Tool.id_selector ("Imgshow"). style.opacity = 1; }            }        }

  6. Finally, throw the Init method that the developer uses to check some parameters and properties
    //the method that exposes the developer to use, can expand freely        varPublicmethods ={init:function(option) {if(Arguments.length = = 0) {//Check parametersThrow NewError ("This method need a config object"); }Else{                    if(document.body.style.opacity = = undefined) {//detects if the opacity attribute is supported [i.e. IE9 and above]                        Throw NewError ("Browser of high version"); }Else{option.config=privatemethods.parahandling (option); Option.selector= "Divshow"; //if it's IE9.                        if(Document.body.style.transition = =undefined)                            {privatemethods.createcontent (option);                        Privatemethods.divfadein (option); } Else{privatemethods.createcontent (option);                    }; }                }            }        }

  7. Test code
    <!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Title</title></Head><Body></Body></HTML><Scriptsrc= "Setbackgroundimage_js.js"></Script><Script>    +(function(){        varTemp={config:{imgarr:["http://z.k1982.com/show_img/201303/2013033012383895.jpg"], Imgsecond: the}} gerry.setBackgroundImage.init (temp); })()</Script>

Summary and Description:

Because the filter below IE8 is troublesome, so there is no processing for IE8, ie9+ because the transparent property is supported. The mobile side has not been tested, but should be available, because the mobile side of the word is more simple, because now the mobile trend is relatively supportive of some common HTML5 and CSS3 familiar. In fact, the above code mainly talk about the idea and IE9 to do compatibility, because can not use the third-party library, so I wrote. The entire code I also do not paste, directly put on GitHub, I hope you point a star praise, get people's appreciation or very motivated.

GitHub address : HTTPS://GITHUB.COM/GERRYISWARRIOR/SETBACKGROUNDIMAGE_JS

Advanced front-end siege lion: Design native JS plugin using monomer mode

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.