2016-08-10 2 views
1

몇 가지 함수를 노출 할 수 있어야하는 ajaxHelper 모듈을 만들려고하는데 호출 될 때 AJAX 호출에서 검색 한 데이터가있는 도우미 객체를 반환해야합니다. AJAX 호출과 관련된 오류. 여기노출 함수 및 반환 객체

내가 생각하고 무엇을의 라인을 따라 뭔가 :

궁극적으로 채울 것
define("helpers-ajaxDataRetriever", ["jquery"], function ($) { 

    var helper = {}; 

    helper.getIndexData = function() { 
     fnIndexData(); 
     return helper; 
    } 

    var fnIndexData = function() { 
     $.ajax({ 
      url: nwatchBaseUrl + '/api/HomeApi/NodeSummary' 
     }).success(function (returnedData) { 
      helper.success = true; 
      helper.data = returnedData; 
     }).fail(function (jqXHR, textStatus) { 
      helper.success = false; 
      helper.error.jqXHR = jqXHR; 
      helper.error.textStatus = textStatus; 
     }); 
    } 

}); 

그때 기능 (예 : getIndexData 등)를 호출 할 수 있도록이 ajaxHelper을 가져 다른 모듈을 원하는, 헬퍼 객체를 생성 한 다음 부울 성공, 데이터 또는 오류 객체와 같은 다양한 속성을 참조 할 수 있어야합니다.

어떻게해야합니까?

답변

1

예상대로 작동하려면 모듈이 외부 세계에 공개하려는 속성을 반환해야합니다 (다른 모듈에서 사용하기 위해).

ajax이 비동기 적이기 때문에 직접 변수에 액세스하는 대신 콜백을 사용하여 이러한 시나리오를 해결하는 것이 좋습니다. ajax 호출이 성공적으로 완료되고 데이터를 반환하는시기를 알 수 없으므로. 우리는 위의 예에서 getIndexData을 노출 할 이후

define("helpers-ajaxDataRetriever", ["jquery"], function($) { 

    var helper = {}; 
    // you will pass in the options 
    // which will contains the success and error 
    // callbacks, along with additional props 
    // that you wanna pass in and use 
    helper.getIndexData = function(options) { 
    fnIndexData(options); 
    } 

    var fnIndexData = function(options) { 
    $.ajax({ 
     url: options.nwatchBaseUrl + '/api/HomeApi/NodeSummary' 
    }).success(function(returnedData) { 
      options.success && options.success.apply(null, arguments); 
    }).fail(function(jqXHR, textStatus) { 
     options.error && options.error.apply(null, arguments); 
    }); 
    } 

    // You return the object, which are the public methods 
    // or properties which you wanna expose when this module is used 
    return { 
    getIndexData: getIndexData 
    } 
}); 

// This is when you wanna use the above exposed function 
// in any module 
define("use-ajax", ["helpers-ajaxDataRetriever"], function(customAjax) { 

    var options = { 
     success: function(data) { 
      console.log('success'); 
      // use the data 
     }, error: function(jqXHR, textStatus) { 
      console.log('failure'); 
      // you will have access to the 
      // arguments of the error function here 
     }, 
     nwatchBaseUrl: 'https://google.com/' 
    } 

    customAjax.getIndexData(options); 
}); 

, 우리는 완전히 헬퍼 공간을 없애 단지 함수 정의를 반환 할 수 있습니다.

또한 promise

의 개념을 사용하여 저장을 달성 할 수