2011-12-02 2 views
44

나는 RequireJS에 관한 여러 튜토리얼을 읽기 시작했다. 그들 중 어느 누구도 "정의"키워드가 만족스럽게 나를 설명하지 못했습니다. 누군가가 다음을 도와 줄 수 있습니까?RequireJS 라이브러리의 정의에 대한 설명

define(
    ["Models/Person", "Utils/random", "jquery"], 
    function (Person, randomUtility, $) {..} 
) 

"정의"란 무엇입니까? 배열과 익명 함수가있는 함수를 정의합니까? 아니면 다른 것입니까? 누군가가 이런 종류의 정의에 대해 더 많은 정보를 줄 수 있습니까?

추가 : 답변 해 주셔서 감사합니다. nnnnnn 및 pradeek. 여기에 유럽에서 나는 질문을 게시 할 때 밤 2시 30 분이었다. 어쩌면 나는 단순한 함수 호출이라는 것을 알지 못했을 것이다.

답변

57

define은 RequireJS에만 해당되는 것이 아니라 AMD specification의 일부입니다. 버크 (Burke)는 RequireJS가 AMD가 명시한 방식을 정확히 구현하지 못한다는 점을 지적했다. AMD가 브라우저를 염두에 두지 않았기 때문이다.

define에는 익명의 기능이 없습니다. define은 AMD 기반 JavaScript 파일에서 데이터로드를 위해 사용할 수있는 방법입니다. RequireJS와 같은 라이브러리는 이것을 사용할 수있게합니다. 특정 구현은 아마도 당신에게 가치가 없습니다. 모듈을 선언하는 가장 일반적인 방법 인 것처럼 제공 한 모듈을 살펴 보겠습니다.

define([array] , object);

배열이 모듈에 의존하는 모듈의 목록이다. 모듈과 파일간에 1 대 1의 관계가 있습니다. 하나의 파일에는 여러 개의 모듈을 가질 수 없으며 하나의 모듈에는 여러 개의 파일을 가질 수 없습니다.

개체는 정의 할 모듈입니다. 이것은 구조체 또는 구조체를 반환하는 함수 일 수 있습니다. 자세한 내용은 RequireJS에있는 문서를 참조하십시오.

object가 함수이면 함수에 전달 된 인수는 첫 번째 define 인수에 종속성으로 나열된 모듈입니다. 함수를 object으로 전달할 때보 다 한 번만 실행된다는 점에 유의해야합니다. 이 하나의 인스턴스화에서 작성된 메소드 또는 특성은 언제든지 액세스 할 수 있지만이 모듈을 종속성으로 나열하는 다른 모듈에서 액세스 할 수 있습니다.

행운을 빈다, 나는 이것으로 놀고, 일이 이해되지 않을 때 문서를 읽는 것이 좋습니다. RequireJS 문서는 AMD 모듈의 작동 방식에 대한 빠른 시작으로 매우 좋습니다.

1

이 페이지에서 찾을 수 있습니다. Why AMD? 매우 도움이됩니다. 이 페이지에서 요약하면 AMD 사양은 "수동으로 주문해야하는 암시 적 종속성을 가진 스크립트 태그 묶음 쓰기"문제를 해결하는 데 도움이됩니다. Python과 같은 다른 프로그래밍 언어에서 import과 비슷한 필수 기능을 실행하기 전에 종속성을로드하는 데 유용합니다. AMD는 또한 글로벌 네임 스페이스 오염 문제를 방지합니다. "It is an improvement over the web's current "globals and script tags" because" 섹션을 확인하십시오.

5

define은 요구 사항의 맨 아래에 정의되어 있습니다.JS는 (나도이 define 단어가있는 것은 어떤 종류의 궁금 해서요, 이것은 내가 찾던 대답 입니다) : 나는 RequireJs API specification 꽤 잘 요약 생각

/** 
* The function that handles definitions of modules. Differs from 
* require() in that a string for the module should be the first argument, 
* and the function to execute after dependencies are loaded should 
* return a value to define the module corresponding to the first argument's 
* name. 
*/ 
define = function (name, deps, callback) { 
    var node, context; 

    //Allow for anonymous modules 
    if (typeof name !== 'string') { 
     //Adjust args appropriately 
     callback = deps; 
     deps = name; 
     name = null; 
    } 

    //This module may not have dependencies 
    if (!isArray(deps)) { 
     callback = deps; 
     deps = null; 
    } 

    //If no name, and callback is a function, then figure out if it a 
    //CommonJS thing with dependencies. 
    if (!deps && isFunction(callback)) { 
     deps = []; 
     //Remove comments from the callback string, 
     //look for require calls, and pull them into the dependencies, 
     //but only if there are function args. 
     if (callback.length) { 
      callback 
       .toString() 
       .replace(commentRegExp, '') 
       .replace(cjsRequireRegExp, function (match, dep) { 
        deps.push(dep); 
       }); 

      //May be a CommonJS thing even without require calls, but still 
      //could use exports, and module. Avoid doing exports and module 
      //work though if it just needs require. 
      //REQUIRES the function to expect the CommonJS variables in the 
      //order listed below. 
      deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); 
     } 
    } 

    //If in IE 6-8 and hit an anonymous define() call, do the interactive 
    //work. 
    if (useInteractive) { 
     node = currentlyAddingScript || getInteractiveScript(); 
     if (node) { 
      if (!name) { 
       name = node.getAttribute('data-requiremodule'); 
      } 
      context = contexts[node.getAttribute('data-requirecontext')]; 
     } 
    } 

    //Always save off evaluating the def call until the script onload handler. 
    //This allows multiple modules to be in a file without prematurely 
    //tracing dependencies, and allows for anonymous module support, 
    //where the module name is not known until the script onload event 
    //occurs. If no context, use the global queue, and get it processed 
    //in the onscript load callback. 
    (context ? context.defQueue : globalDefQueue).push([name, deps, callback]); 
}; 
0

:

모듈에 종속성이있는 경우 첫 번째 인수는 종속성 이름의 배열이어야하고 두 번째 인수는 정의 함수 여야합니다. 모든 종속성이로드되면 함수를 호출하여 모듈을 정의합니다. 함수는 모듈을 정의하는 객체를 반환해야합니다.

여기에는 정의의 다양한 구문 형식의 예가 나열되어 있습니다.