无法在Mouseup事件上传递回调函数 - JavaScript

时间:2017-08-09 22:40:25

标签: javascript google-chrome-extension

我正在尝试将回调函数作为参数传递给前一个函数,该函数由chrome扩展中的mouseup触发。所以基本上我的目标是在lwsGetText完成运行后立即触发quickTranslate函数。但我无法弄清楚如何执行此操作,因为函数lwsGetText是由mouseup触发的。这是我的代码:

内容脚本(js)

(function () {

    // Holds text being selected in browser
    var lwsSelectedText = '';

    // Adds pop-up to current webpage
    function lwsAddContent(callback) {

        // Get body tag
        var body = document.getElementsByTagName('body');

        // add invisible div
        document.body.innerHTML += '<div id="myModal" class="modal"><div class="modal-content"><span class="close">&times;</span><div id="lwsSpanishDiv"><p id="lwsSpanishTitle">Spanish</p><textarea id="lwsSpanishTextArea">Hello</textarea></div><div id="lwsEnglishDiv"><p id="lwsEnglishTitle">English</p><textarea id="lwsEnglishTextArea">Hello 2</textarea></div></div></div>';

        callback(lwsSetUpTextGetter);

    }

    // Make the pop-up visible and set up close button
    function lwsActivateContent(callback) {

        var modal = document.getElementById('myModal');

        // Get the textarea
        var txtarea = document.getElementById("myTxtArea");

        // Get the <span> element that closes the modal
        var span = document.getElementsByClassName("close")[0];

        span.onclick = function () {
            modal.style.display = "none";
        }

        callback(quickTranslate);

    }

    // Initialize ability to select and grab text from browser
    function lwsSetUpTextGetter(callback) {
        //Set the onmouseup function to lwsGetText
        document.onmouseup = lwsGetText;
        //Handling clicking outside webpage?
        if (!document.all) document.captureEvents(Event.MOUSEUP);


    }

    //Gets selected text
    function lwsGetText(callback,e) {

        // Get access to spanish text area
        var spanishText = document.getElementById('lwsSpanishTextArea');

        //Get text
        lwsSelectedText = (document.all) ? document.selection.createRange().text : document.getSelection();

        //if nothing is selected, do nothing
        if (lwsSelectedText != '') {

            // test: does browser grab text correctly?
            alert(lwsSelectedText);

            // Set spanish text area content to the selected text from browser
            spanishText.value = lwsSelectedText;

            // --Error Here--
            callback();

        }

    }

    function quickTranslate() {

        alert("Quick Translate");

        var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
        keyAPI = "trnsl.1.1.20130922T110455Z.4a9208e68c61a760.f819c1db302ba637c2bea1befa4db9f784e9fbb8";

        var englishTextArea = document.getElementById('lwsEnglishTextArea');
        var spanishTextArea = document.getElementById('lwsSpanishTextArea');

        englishTextArea.value = 'Working...';

        var xhr = new XMLHttpRequest(),
            textAPI = spanishTextArea.value,
            langAPI = 'en';
        data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(data);
        xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                var res = this.responseText;
                var json = JSON.parse(res);
                if (json.code == 200) {
                    englishTextArea.value = json.text[0];
                }
                else {
                    englishTextArea.value = "Error Code: " + json.code;
                }
            }
        }

    }


    // When document ready
    $(document).ready(function () {

        lwsAddContent(lwsActivateContent);

    });

})();

如果有人可以帮我弄清楚如何将quickTranslate函数实现为回调函数,那就太棒了!谢谢!

1 个答案:

答案 0 :(得分:1)

如您所知,您分配的事件处理程序需要一个参数,即事件。但是,您可以通过执行以下操作来创建围绕“回调”变量的闭包:

function lwsGetText(callback) {
  return function (e) {

    // Get access to spanish text area
    var spanishText = document.getElementById('lwsSpanishTextArea');

    //Get text
    lwsSelectedText = (document.all) ? document.selection.createRange().text : document.getSelection();

    //if nothing is selected, do nothing
    if (lwsSelectedText != '') {

        // test: does browser grab text correctly?
        alert(lwsSelectedText);

        // Set spanish text area content to the selected text from browser
        spanishText.value = lwsSelectedText;

        // --Error Here--
        callback();

    }
  };
}

然后在设置处理程序时将值quickTranslate作为“回调”参数传递,不知道你是怎么做的,所以这是猜测:

myElement.addEventListener("mouseup", lwsGetText(quickTranslate));