How to structure my javascript/jquery code?

前端 未结 10 899
我寻月下人不归
我寻月下人不归 2020-12-12 09:22

I am toying around with a pretty intensive ajax based jquery web application. It is getting to a point where I almost loose track of what events that should trigger what act

相关标签:
10条回答
  • 2020-12-12 10:10

    To add to the existing answers, here's a great post that covers more advanced techniques that build on the Module Pattern.

    Once your Javascript code reaches a certain size, you'll inevitably want to refactor it by breaking it into multiple files / modules / sub-modules. If you're not sure how to accomplish this using the module pattern, this article is a must-read.

    0 讨论(0)
  • 2020-12-12 10:12

    AMDS!

    It's been awhile since first answers got posted to this question and many things have changed. First and foremost, the JS browser world seems to be moving towards AMDs (asynchronous module definition) for code organization.

    The way that works is you write ALL your code as AMD modules, e.g.:

    define('moduleName', ['dependency1', 'dependency2'], function (dependency1, dependency2) {
        /*This function will get triggered only after all dependency modules loaded*/
        var module = {/*whatever module object, can be any JS variable here really*/};
        return module;
    });
    

    And then modules get loaded using AMD loaders like curl.js or require.js etc, for example:

    curl(
        [
            'myApp/moduleA',
            'myApp/moduleB'
        ],
    ).then(
        function success (A, B) {
            // load myApp here!
        },
        function failure (ex) {
            alert('myApp didn't load. reason: ' + ex.message);
        }
    );
    

    Advantages are:

    1. You only have to include single <script> element on your page that loads AMD loader itself (some of them are quite tiny).

    2. After that all JS files will be fetched automatically in asynchronous NON BLOCKING! fashion, thus way faster!

    3. Necessary modules will get executed only after its dependencies got loaded.

    4. Modular (which means code that is easier to maintain and re-use).

    5. Global variables pollution can be completely curbed if used correctly.

    Honestly, once concept has clicked in your head, you'll never go back to your old ways.

    P.S: jQuery does register itself as AMD module starting from version 1.7.

    More information on AMDS:

    • https://github.com/cujojs/curl
    • http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition
    • http://requirejs.org/
    • http://www.bennadel.com/blog/2275-Using-RequireJS-For-Asynchronous-Script-Loading-And-JavaScript-Dependency-Management.htm
    • https://github.com/Integralist/Blog-Posts/blob/master/2012-01-04-Beginners-guide-to-AMD-and-RequireJS.md
    0 讨论(0)
  • 2020-12-12 10:21

    My js files usually follow a naming convention similar to this :

    • xxx.utility.js
    • mypage.events.js
    • xxx.common.js
    • /lib/
    • /OS-DoNotDistribute/lib/

    Where

    • 'mypage' is the name of the html, aspx, php, etc file.
    • 'xxx' is the concept. (i.e. orders.common.js)
    • 'utility' signifies it's a reusable library script (i.e. ajax.utility.js, controlfader.utility.js)
    • 'common' is reusable functionality for this app, but not reusable across other projects
    • 'lib' is a subdirectory for any external or library scripts
    • 'OS-DoNotDistribute' is a subdirectory to ensure no OS licensed code is distributed if the app is ever sold.

    Also, for ajax, I have a special naming convention for call back functions, so it's easy to tell what they are.

    I'm not sure it that's close to what you were looking for, but I hope it helps.

    0 讨论(0)
  • 2020-12-12 10:28

    To keep my events in control I use a publish/subscribe mechanism

    jQuery.subscribe = function( eventName, obj, method ){
        $(window).bind( eventName, function() {
            obj[method].apply( obj, Array.prototype.slice.call( arguments, 1 ) );
        });
        return jQuery;
    }
    
    jQuery.publish = function(eventName){
        $( window ).trigger( eventName, Array.prototype.slice.call( arguments, 1 ) );
        return jQuery;
    }
    

    Here's an example of its use

    // a couple of objects to work with
    var myObj = {
        method1: function( arg ) {
            alert( 'myObj::method1 says: '+arg );
        },
        method2: function( arg1, arg2 ) {
            alert( arg1 );
            //republish
            $.publish( 'anEventNameIMadeUp', arg2 );
        }
    }
    
    var myOtherObj = {
        say: function(arg){
            alert('myOtherObj::say says: ' + arg);
        }
    }
    
    
    
    // you can then have all your event connections in one place
    
    //myObj::method2 is now listening for the 'start' event 
    $.subscribe( 'start', myObj, 'method2' );
    
    //myOtherObj::say is now listening for the 'another' event
    $.subscribe( 'anotherEvent', myOtherObj, 'say' );
    
    //myObj::method1 is now listening for the 'anEventNameIMadeUp' event
    $.subscribe( 'anEventNameIMadeUp', myObj, 'method1' );
    //so is myOtherObj::say
    $.subscribe( 'anEventNameIMadeUp', myOtherObj, 'say' );
    
    
    // ok, trigger some events (this could happen anywhere)
    $.publish( 'start', 'message1', 'message2' );
    $.publish( 'anotherEvent', 'another message' );
    
    0 讨论(0)
提交回复
热议问题