2017-06-22 85 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