Program Tip

내 javascript / jquery 코드를 구성하는 방법은 무엇입니까?

programtip 2020. 11. 15. 11:38
반응형

내 javascript / jquery 코드를 구성하는 방법은 무엇입니까?


나는 꽤 집약적 인 ajax 기반 jquery 웹 응용 프로그램을 가지고 놀고 있습니다. 어떤 행동 등을 유발해야하는 이벤트를 거의 잃어버린 지점에 도달하고 있습니다.

좀 더 기본적인 수준에서 내 자바 스크립트 구조가 잘못되었다는 느낌이 남아 있습니다. 자바 스크립트 / jquery 코드, 이벤트 처리 등을 어떻게 구성합니까? 초보자 자바 스크립트 개발자를위한 조언.


AMDS!

이 질문에 대한 첫 번째 답변이 게시되고 많은 것이 변경된 지 오래되었습니다. 무엇보다도 JS 브라우저 세계는 코드 구성을 위해 AMD (비동기 모듈 정의)로 이동하는 것 같습니다.

작동하는 방식은 모든 코드를 AMD 모듈로 작성하는 것입니다. 예 :

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;
});

그런 다음 curl.js 또는 require.js 등과 같은 AMD 로더를 사용하여 모듈을로드합니다 .

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

장점은 다음과 같습니다.

  1. <script>페이지에 AMD 로더 자체를로드하는 단일 요소 만 포함하면됩니다 (일부는 매우 작습니다).

  2. 그 후 모든 JS 파일은 비동기 NON BLOCKING에서 자동으로 가져옵니다! 패션, 따라서 훨씬 빠릅니다!

  3. 필요한 모듈은 종속성이로드 된 후에 만 ​​실행됩니다.

  4. 모듈 식 (유지 관리 및 재사용이 더 쉬운 코드를 의미 함).

  5. 전역 변수 오염은 올바르게 사용하면 완전히 억제 될 수 있습니다.

솔직히 개념이 머릿속에서 클릭 되면 이전 방식으로 돌아 가지 않을 것입니다.

추신 : jQuery는 버전 1.7부터 AMD 모듈로 등록합니다.

AMDS에 대한 추가 정보 :


자바 스크립트 코드의 경우 Christian Heilmann의 다음 링크가 필수 불가결하다는 것을 알았습니다.

여기 Peter Michaux가 설명한 방법도 정말 마음에 듭니다.

jQuery의 경우 Authoring에 대한 가이드를 읽는 것이 좋습니다 . jQuery 플러그인 패턴 에 대한이 튜토리얼은 매우 좋습니다.


이벤트를 제어하기 위해 발행 / 구독 메커니즘을 사용합니다.

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;
}

다음은 그 사용의 예입니다.

// 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' );

I definitely recommend reading up on the object literal pattern in addition to the module pattern; here's a good writeup:

http://ajaxian.com/archives/show-love-to-the-object-literal


(function($, window, slice)
{

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

    $.publish = function(eventName)
    {
        $(window).trigger(eventName, slice.call(arguments, 1));
        return jQuery;
    };

})(jQuery, window, Array.prototype.slice);

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.


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.


I really like these articles:

http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html

http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/

They helped me to understand how telerik creates extensions for asp.net mvc.


I like the idea of AMDs (see nix's answer).

But I typically compile all my JS files into one JS file. In that case the asynchronous part is not needed. So I wrote a little "Infile Module Loader".

Here it is: https://codereview.stackexchange.com/questions/14530/a-little-infile-amd


We can use mvc pattern in our javascript-jquery applications. (Backbone.js, knockout.js vs.... ) are mature libraries we can use for this aim.

참고URL : https://stackoverflow.com/questions/528648/how-to-structure-my-javascript-jquery-code

반응형