Front-end Programming Improvement Tour (11)----The organization of jquery code

Source: Internet
Author: User

recently do in-push project, although the project is not too big, or encountered some code organization problem, in the final analysis or the overall project control is not enough, for this Yue Timor specifically in the network gathered some jquery code organized articles and summed up two ways to better organize jquery code.

first, the callback function

Definition of callback function:

A callback is a function of passed as an argument to another function and is executed after its parent function h As completed.

The callback is to pass a function as a variable, passing in another function. The former will be executed upon completion of the latter execution.

The simple callback example above shows that the function parameter can be a function, which is the basis of the jquery callback function usage.

function Hidesearcharea (callback) {                $ (". Search-area-container"). Hide ();                var width = searcharea.width ();                Searcharea.animate ({"Left":-width}, +, function () {                    if (callback) {                        callback ()}                    }                );            } Btnsearch.click (function () {                var KeyWord = $ (' #keyWord '). Val ();                var locid = $ ("#citySelect"). Val ();                if (KeyWord = = Oldsearchdata.keyword && Locid = = oldsearchdata.locid) {                    hidesearcharea ();                    return false;                } Old data does not return data                Hidesearcharea (function () {                    joblist.empty ();                    pagenum = 1;//Empty page number                    getinternalrecommendjobadlist (KeyWord, locid);//Load Search item                });//Use callback, eliminate the problem of parameter-passing            }) ;

Callback is also used in the project, in the above code example, the benefit of the callback is to omit the complex function of the process of the transfer of parameters, in the Click event defined in the local variables, directly into the Hidesearcharea function callback, eliminating the excess variable control parameter transfer.

Two, the jquery Code organization Essentials

    • 1. Resolve the eliminate anonymous function.
    • 2. Centered on the configuration parameters.
    • 3. Unify the event listener within a function.
    • 4. Encapsulate the entire program segment into a single function, leaving only the unique interface to the outside to facilitate large project code organization.
Here's a simple example to look at the application of code organization: HTML structure:
<ul id= "Myfeature" >        <li>hi oop</li>    </ul>

jquery Code:
var myfeature = {////First class instance properties are defined in this.xxx form, class attributes are defined in classname.xxx form///The following functions and configuration objects are configured with the jquery object parameters for class properties//initialization and invoke the event binding setting function            Within the class, the object is substituted with _this for easy marking of init:function (settings) {_this = Myfeature; _this.config = {$items: $ (' #myFeature Li '), $container: $ (' <div class= "contain            ER "></div>"),}; $.extend (_this.config, Settings | |            {});        _this.setup ();            },//Event binding set function for binding events, communicating jquery object with response event Setup:function () {var item = _this.config. $items;        Item.each (_this.createcontainer). Click (_this.showitem); },//create Div under Li and set Data createcontainer:function () {var $i = $ (this), $c = _this.config            . $container. Clone (). AppendTo ($i);        $i. Data (' container ', "Hello World");            }, Showitem:function () {_this. $currentItem = $ (this); _this.getcontent ();        }, Getcontent:function () {var txt = _this. $currentItem. Data (' container ');        $ (". Container"). HTML (TXT); },};$ (function () {myfeature.init ();});  

from this code is not difficult to see, the above code to organize ideas.
    • Uniformly writes a DOM object to a configuration (config) object
    • Uniformly write event listener objects to the Setup function (Setup)
    • Configuration properties and installation functions are called in the initialization function (init) function
    • The Setup function event listener function uses the function callback method to call this kind of function function
    • The initialization (init) method of this class is called at the entrance of the entire program
The above procedure has a disadvantage,that is, the class method can be accessed externally.
the above method is further optimized to change the entire object into a self-executing function, then the return value of the initialization object is the only external interface, the internal orchestration does not consider the problem of object reference, in essence, is still oriented to process programming, but the code management has done a very good package. The code is as follows:
var feature = (function () {        var  $items = $ (' #myFeature Li '), $container = $ (' <div class= "container" ></di V> '), $currentItem,        init = function (settings) {            setup ();        },//initialization function        setup= function () {           var item = $items. Each (CreateContainer)            . Click (showitem);        },//binding function        CreateContainer = function (idx) {            var $i = $ (this),            $c = $container. Clone ()            . AppendTo ($i);            $i. Data (' container ', "Hello World")        ,        showitem = function () {            $currentItem = $ (this);            GetContent ();        },        getcontent = function () {            var txt = $currentItem            . Data (' container ');            $ (". Container"). HTML (TXT);        };        return {            init:init//external interface        };    }) ();    Feature.init ();//initialization function

As shown in the code above, the four points mentioned above can be implemented. But given that the push project script is executed individually for each page, this organization is not used. But the whole idea still uses the above method. That is, the first three points are implemented, and the code implementation is written in the second code.

Iii. References 1. Users: http://www.zhihu.com/question/26348002 2.36 Persons Library: http://www.xue163.com/121/6/1212972.html 3.csdn User: http://blog.csdn.net/dananhai381/article/details/6709934

Front-end Programming Improvement Tour (11)----The organization of jquery code

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.