내 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);
}
);
장점은 다음과 같습니다.
<script>
페이지에 AMD 로더 자체를로드하는 단일 요소 만 포함하면됩니다 (일부는 매우 작습니다).그 후 모든 JS 파일은 비동기 NON BLOCKING에서 자동으로 가져옵니다! 패션, 따라서 훨씬 빠릅니다!
필요한 모듈은 종속성이로드 된 후에 만 실행됩니다.
모듈 식 (유지 관리 및 재사용이 더 쉬운 코드를 의미 함).
전역 변수 오염은 올바르게 사용하면 완전히 억제 될 수 있습니다.
솔직히 개념이 머릿속에서 클릭 되면 이전 방식으로 돌아 가지 않을 것입니다.
추신 : jQuery는 버전 1.7부터 AMD 모듈로 등록합니다.
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
자바 스크립트 코드의 경우 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
'Program Tip' 카테고리의 다른 글
테마 옵션에 대한 WordPress 3.5 사용자 정의 미디어 업로드 (0) | 2020.11.15 |
---|---|
include_recipe를 사용하거나 run_list에 레시피를 추가해야합니까? (0) | 2020.11.15 |
RESTful API 문서화를위한 표준 방법 (0) | 2020.11.15 |
DLL 파일을 포함하는 JAR 파일을 만드는 방법은 무엇입니까? (0) | 2020.11.15 |
Qt가 예외 처리를 사용하지 않는 이유는 무엇입니까? (0) | 2020.11.15 |