2013-12-07 148 views
2

誰能告訴我爲什麼這不起作用?未調用外部函數 - javascript

ui = (function() { 
collabElement = document.getElementById('approveCollab'); 
    if(collabElement) 
     collabElement.onclick = function(){editor.collaborate(); removeOverlay();} 

    deleteElement = document.getElementById('approveDelete'); 
    if(deleteElement) 
     deleteElement.onclick = function(){editor.deletePost(); removeOverlay();} 
})(); 

「協作」是「editor.js」文件中的導出函數。 removeOverlay()」是在同一個文件的功能。 當‘collabElement’點擊只有‘removeOverlay’被調用。

沒有錯誤,只是該功能沒有被調用。

這些都是editor.js內被調用的函數:

function collaborate(event) { 

    console.log("started"); 
    var url = ''; 

    var postID = document.querySelector('.save').getAttribute('id'); 
    var recipient = document.querySelector('.collab-input').value; 

    //validate email syntax 
    var atpos=recipient.indexOf("@"); 
    var dotpos=recipient.lastIndexOf("."); 
    if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){ 
     console.log("wrong email"); 
     document.querySelector('.email-error').style.display = "block"; 
    } 
    else{ 
     console.log("sending email to " + recipient); 
     document.querySelector('.email-error').style.display = "none"; 
     if(postID != "new"){ 
      url = url + "?id=" + postID + "&recipient=" + recipient; 

      var request = new XMLHttpRequest(); 
      request.open("GET", "collaborate"+url, true); 
      request.send(); 
     } 
    } 
} 

function deletePost(event) { 

    var url = ''; 

    var postID = document.querySelector('.save').getAttribute('id'); 
    if(postID != "new"){ 
     url = url + "?id=" + postID; 

     var request = new XMLHttpRequest(); 
     request.open("GET", "delete"+url, true); 
     request.send(); 
    } 
} 

回答

4

如果你想調用一個函數,可以給它添加()

editor.collaborate() 

(而不是editor.collaborate,這將僅僅只解決了功能)

+0

謝謝彼得。顯然,你是對的:) 雖然加入()時,我得到一個錯誤 對象#沒有方法'協作'。 當爲另一個功能做同樣的工作就好了。 – omerkarj

+0

然後對象編輯器沒有這種方法。 editor.js是否位於公共網址上,以便我可以查看它? –

+0

看我編輯的問題以供參考。 deletePost()函數工作得很好。我真的沒有得到這個... – omerkarj

2

我懷疑的問題是,你的IIFE不返回任何東西; UI將永遠是不確定的,我認爲你想這樣的:

ui = (function() { 
    collabElement = document.getElementById('approveCollab'); 
    if(collabElement) 
     collabElement.onclick = function(){editor.collaborate; removeOverlay();} 
    //return collabElement so it's assigned to ui 
    return collabElement; 
})(); 

編輯

雖然這是真的你IIFE不返回任何東西,它看起來像彼得的回答是更相關的,以你的那一刻;協作沒有被調用。他似乎是這個問題的正確答案。

+0

感謝亞當,我只是複製了一些該函數的代碼中,我通過返回的init(初始化),其中要求所有相關功能。 – omerkarj