2012-11-05 4 views
4

사용자가 보고서를 작성할 수있는 단일 페이지 응용 프로그램을 만들었습니다. 사용자는 데이터 소스, 차트 유형 및 테마를 선택할 수있는 양식을 제공 받고, 확인시 페이지가 필요한 파일을로드하고 차트를 그립니다.약속으로 모듈로드를 구현할 수 있습니까?

더 나은 성능을 위해 코드 모듈과 데이터를 병렬로로드하고 싶습니다.

가 은 (JS 모듈 원형 차트가로드) 및 (블루 테마 CSS가로드) 및 (항공 통계 JSON이다

WHEN 예를 들어, 사용자는 "파이 차트", "블루 테마 '및'항공 기록"을 선택하면 로드)

THEN (

나는 모듈 로딩과 약속이 내 위의 예에서와 같이 결합 될 수있는 AMD를 구현하는 라이브러리의 수, 약속을 구현하는 라이브러리의 수 있지만 없음을 발견했다) 차트를 그릴 . 이것이 가능한가, 이미 이것을 구현 한 라이브러리가 있는가?

내 클라이언트 자바 스크립트가 필요합니다.

답변

1

jQuerypromises을 통해 실제로 수행 할 수 있습니다. 그것은 단지 코드를 수정하는 문제입니다.

코드를 소유하고 있고 모든 코드가 in the same domain이거나 크로스 도메인 인 경우 allows CORS이라고 가정하면 각각 .ajax()이로드됩니다. 그런 다음 .when()을 사용하여 모든 약속이로드 된시기를 감지하고 .then()은 모든 약속 해결을 실행하기 위해 콜백을 추가합니다.

//you can provide a detailed setting for each using .ajax()'s second parameter 
//however, jQuery can "smart detect" the content's dataType 

var chart = $.ajax(urlOfChart), //script 
    theme = $.ajax(urlOfTheme), //css 
    data = $.ajax(urlOfData); //JSON 

//we use .when() to check when all three resolves 
//the arguments will be the jqXHR objects for the requests 
//in the order they were given in the argument list 
$.when(chart,theme,data).then(function(chart,theme,data){ 

    //according to jQuery.ajax(), if a script is requested, it is evaluated 
    //and we still get it's plain text content 
    //so with respect to the script, we do no processing 

    //with the css, we get it as plain text since no dataType value handles it 
    //we embed it into the DOM by creating a style element 
    //and append the text in it for the styles to take effect on the page 
    $('<style type="text/css" />').html(theme).appendTo('head'); 

    //as for the JSON, jQuery converts it into an object 
    //and is passed as an argument as the return data for that promise 

    //...everything is now requested, retrieved and prepared... 
    //everything else goes under here 

}); 
1

CommonJS 모듈은 요구 사항이 정의되면 각 팩토리가 호출되기 때문에 약속되어 있습니다.

따라서 데이터를 모듈로 정의하고 코드를 'js', 'css', 'data'가 필요한 모듈로 정의하면 실제로는 바로 사용할 수 있습니다.

또는 CommonJS/AMD 상단의 추상화, CSS로드 (예 : LABJS?) 및 데이터로드 (xhr/jsonp)를 통해 약속을 사용합니다.

+0

맞아요, 데이터를 모듈로 정의하는 것도 효과가 있습니다. 어떻게해야할지 모릅니다. 구체적인 예나 튜토리얼을 가르쳐 주시겠습니까? – Christophe

+0

다른 모듈은 어떻게 정의됩니까? 그냥 그렇게. 예를 들어, AMD에서는'define ('mydata', {.....}) 또는 이와 비슷한 것을 호출합니다. –

+0

Dojo Toolkit의 모듈을 그대로 사용하여 AMD에 익숙하지 않았습니다. 이것은 완벽한 의미로, 단지 그것을하는 법을 배워야합니다. 도와 주셔서 감사합니다! – Christophe

관련 문제