2017-06-22 83 views
0

我已經閱讀了一些關於回調的好消息,雖然我將它們用於點擊事件和類似事件,但是我沒有充分理解它們而使用它們。另一個Javascript回調問題/示例

我有一個簡單的網頁應用程序,有3或4個html頁面,每個頁面都有自己的js頁面。

我有一些全局函數,我把它放在一個新的js頁面,每個html頁面都需要它引用它。我使用這個文件word_background.js來保存冗長且被多個頁面使用的函數。

pullLibrary是一個函數,駐留在word_background.js中,它從我的db中抽取並處理結果。

我想從webpageOne.html調用pullLibrary,確保它完成,然後在webpageOne.js中執行更多處理。

在webpageOne.js中,我有以下內容 - 嘗試撥打pullLibrary,一旦完成,請將結果用於webpageOne.js中的進一步工作。

該代碼執行pullLibrary(在word_background.js中),但不會「返回」到webpageOne.js以繼續處理。

我假設我缺少回調一些關鍵的,重要的方面...

我只是想運行pullLibrary功能(其中有Ajax調用等),一旦它是完整的,請繼續我的頁面設置。

任何解釋/更正讚賞。

此代碼是webpageOne.js:

pullLibrary(function(){ 
    console.log('Now processing library...'); 
    processLibrary(); 
    updateArrays(); 
    //Do a bunch more stuff 
}); 

----- ----- UPDATE

謝謝你的意見......我認爲這是我的啓發打破心理這應該如何工作的模型。

pullLibrary是一個ajax函數 - 它從數據庫中提取並將結果填充到數組和localStorage中。

我的期望是我可以調用pullLibrary,當它完成時,回調代碼(在這種情況下是匿名函數)將運行。

function pullLibrary(){ //Values passed from startup() if no data is local 
    //Pull data from database and create basic LIBRARY array for further processing in processLibrary sub 
console.log("Starting to pull library array in background.js..." + "User: " + localStorage.userID + " License: " + localStorage.licType); 

var url1 = baseURL + 'accessComments3.php'; 
var url2 = '&UserID=' + localStorage.userID + '&LicType=' + localStorage.licType; 

//Need global index to produce unique IDs 
var idIndex = 0; 
var index = 0; 

$.ajax({ 
    type: "POST", 
    url: url1, 
    data: url2, 
    // dataType: 'text', 
    dataType: 'json', 
    success: function(result){ 
    // success: function(responseJSON){ 
    arrLibrary = result; //store for use on this page 
    localStorage.library = JSON.stringify(result); //Store for use elsewhere 
    console.log('Saving to global variable: ') + console.log(arrLibrary); 

    //Now mark last update to both sync storage and local storage so access from other browsers will know to pull data from server or just use local arrays (to save resources) 
    var timeStamp = Date.now(); 
    var temp = {}; 
    temp['lastSave'] = timeStamp; 
    // chrome.storage.sync.set(temp, function() { 
     console.log('Settings saved'); 
     localStorage.lastSync = timeStamp; 
     console.log('Last update: ' + localStorage.lastSync); 

    //Store Group List 
     var arrComGroups = $.map(arrLibrary, function(g){return g.commentGroup}); 
     // console.log('List of comment groups array: ') + console.log(arrComGroups); 
     arrComGroups = jQuery.unique(arrComGroups);  //remove dupes 
     // console.log('Unique comment groups array: ') + console.log(arrComGroups); 

     localStorage.groupList = JSON.stringify(arrComGroups); //Store list of Comment Groups 

    //Create individual arrays for each Comment Groups 
     $.each(arrComGroups,function(i,gName){  //Cycle through each group of Comments 
     var arrTempGroup = []; //to hold an array for one comment group 
     arrTempGroup = $.grep(arrLibrary, function (row, i){ 
      return row.commentGroup == gName; 
     }); 

     //Store string version of each Comment Array 
     window.localStorage['group_' + gName] = JSON.stringify(arrTempGroup); 

     console.log('Creating context menu GROUPS: ' + gName); 
     }); 

    // processLibrary(arrLibrary); //We've pulled the array with all comments - now hand off to processor 

    }, //End Success 

    error: function(xhr, status, error) { 
     alert("Unable to load your library from 11trees' server. Check your internet connection?"); 
     // var err = eval("(" + xhr.responseText + ")"); 
     // console.log('Error message: ' + err.Message); 
    } 

}); //End ajax 

}

+0

您將不得不顯示'pullLibrary()'函數。 – JJJ

+0

你可以發佈一切到服務器或codepen? –

+0

您的問題是您傳遞給'pullLibrary()'的匿名回調函數從未執行?我們需要看看你的'pullLibrary()'函數的代碼 –

回答

0

好,有噸的「這裏是回調的工作方式」的帖子在互聯網上......但我永遠無法得到最簡單的情況晶瑩剔透的例子。

準確度如下?

我們有兩個javascript文件,one.js和two.js.

在one.js中我們有一個函數 - 叫它apple() - 包含一個Ajax調用。

two.js做了大量的處理和偵聽特定的html頁面。它需要來自apple()ajax調用的數據。其他網頁也會使用apple(),所以我們不想只把它放在two.js中。

以下是我現在明白了回調:

one.js:

function apple(callback_function_name){ 

    $.ajax({ 
     type: "POST", 
     url: url1, 
     data: url2, 
     dataType: 'json', 
     success: function(result){ 
      //apple processing of result 
      callback_function_name(); //This is the important part - whatever function was passed from two.js 
     }, //End Success 
     error: function(xhr, status, error) { 
     } 

    }); //End ajax 
} //End apple function 

** ** two.js此 JS文件擁有各類聽衆等

$(document).ready(function() { 
    apple(function(apple_callback){ 
     //all kinds of stuff that depends on the ajax call completing 
     //note that we've passed "apple_callback" as the function callback name...which is stored in the apple function as "callback_function_name". 
     //When the ajax call is successful, the callback - in this case, the function in two.js, will be called back...and the additional code will run 
     //So the function apple can be called by all sorts of other functions...as long as they include a function name that is passed. Like apple(anothercallback){} and apple(thirdcallback){} 
    }); //End apple function 
});  //End Document.Ready