2016-08-10 5 views
1

いくつかの関数を公開できるajaxHelperモジュールを作成しようとしています。呼び出されたときに、AJAX呼び出しから取得したデータを持つヘルパーオブジェクトを返す必要があります。そのAJAX呼び出しに関連するエラー。私はその後、最終的に移入でしょう(例えばgetIndexDataのような)関数を呼び出すことができるように、このajaxHelperをインポートし、他のモジュールを、欲しい関数を公開してオブジェクトを返す

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

}); 

を:ここで

は私が思っていの線に沿って何かでありますヘルパーオブジェクトを作成し、ブール値成功、データ、エラーオブジェクトなどのさまざまなプロパティを参照できるようにします。

これを行うにはどうすればよいですか?

答えて

1

期待通りに動作するためには、モジュールは外部に公開したいプロパティを(他のモジュールで使用するために)返す必要があります。

ajaxは非同期なので、変数に直接アクセスする代わりに、コールバックを使用してこのようなシナリオに取り組むことをお勧めします。 ajaxコールがいつ正常に完了し、データを返すかわからないとき。

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

そして、我々は唯一の上記の例ではgetIndexDataを公開するために、我々は完全にヘルパーの名前空間を取り除くと、ちょうど関数定義を返すことができます。

またpromise

の概念を使用して保存達成できます
関連する問題