无法将函数中定义的变量导出到另一个并发运行的JS文件

时间:2017-06-16 07:53:39

标签: javascript node.js express

我一直在Google和SO上阅读不同的帖子,但我无法弄清楚为什么这不起作用。

在这种情况下涉及2个HTML和2个JS文件(在代码块之后的单词中给出了解释)。

1)index.html

<div id="center">
  <img id="logo" src="../img/logowshadow.png" alt="logo">
  <p id="para">Get your google slides!</p>

  <!--Add buttons to initiate auth sequence and sign out-->
  <button id="authorize-button" style="display: none;">Sign in</button>
  <button id="signout-button" style="display: none;">Sign Out</button>
</div>

<script src="../js/homePage.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
  onload="this.onload=function(){};handleClientLoad()"
  onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

2)homePage.js

var apiKey = 'AIzaSyCSjg3rrx6Obl4ngZsDlFlV4degUJSMvbw';
var discoveryDocs = ["https://slides.googleapis.com/$discovery/rest?version=v1"];
var clientId = '408869653199-ruoft30vmoqrgpku3us3qd2leb3k6tp1.apps.googleusercontent.com';
var scopes = 'https://www.googleapis.com/auth/presentations.readonly https://www.googleapis.com/auth/drive';

var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
var user;
var authResponse;
var oauthToken;
var pickerApiLoaded = false;
var chosenPresentation = null;

function handleClientLoad() {
    // Load the API client and auth2 library
    gapi.load('client:auth2', initClient);
    //Load the Picker API
    gapi.load('picker', onPickerApiLoad);
}

function initClient() {
    gapi.auth2.init({
        apiKey: apiKey,
        discoveryDocs: discoveryDocs,
        clientId: clientId,
        scope: scopes
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
      // Set the current Google User
      gapi.auth2.getAuthInstance().currentUser.listen(updateUser);
      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
}

// Callback to make sure that the Picker API has loaded
function onPickerApiLoad() {
  pickerApiLoaded = true;
  createPicker();
}

// Store the current Google user
function updateUser(gUser) {
  user = gUser;
  updateToken();
}

// Store the access token
function updateToken() {
  authResponse = user.getAuthResponse(true);
  oauthToken = authResponse.access_token;
}

function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
      createPicker();
    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
    }
}
function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
}

// Create and render a Picker object for picking user slides
function createPicker() {
    if (pickerApiLoaded && oauthToken) {
      var picker = new google.picker.PickerBuilder().
        addView(google.picker.ViewId.PRESENTATIONS).
        setOAuthToken(oauthToken).
        setDeveloperKey(apiKey).
        setCallback(pickerCallback).
        build();
      picker.setVisible(true);
    }
}

// Callback implementation
function pickerCallback(data) {
      var url = 'nothing';
      if(data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
        var doc = data[google.picker.Response.DOCUMENTS][0];
        url = doc[google.picker.Document.URL].replace('edit', 'present');
        var item_name = doc[google.picker.Document.NAME];
        alert('You picked ' + item_name);
        //export the chosen presentation for use in mobileControl.js
        chosenPresentation = doc[google.picker.Document.ID];
        alert("chosen: " + chosenPresentation);
        exports.chosenPresentation = chosenPresentation;
        window.location.replace(url);
    }
}

3)mobile.html

<div id="instructions">
    <p>Swipe <b>left</b> to go to the previous slide.</p>

    <p>Swipe <b>right</b> to go to the next slide.</p>
</div>

<script src="../js/mobileControl.js"></script>

和4)mobileControl.js

alert("Loaded the JavaScript!"); //Shows up

var m = require('./homePage.js');
alert("imported"); //Does not show up
alert(m.chosenPresentation); //Does not show up

要说明我的代码试图实现的目标:用户将能够登录其Google帐户,并选择在其Google云端硬盘上找到的一组演示文稿。我想将演示文稿ID从homePage.js传递到mobileControl.js,我尝试使用节点exports。我怀疑它不起作用,因为两个脚本都是“同时运行”(index.html意味着在计算机上运行,​​而mobile.html在移动设备上运行......同时运行)。但是我不确定我是否正确地确定原因,如果是这样,有没有办法在定义后从函数中导出变量?也许我应该在选择幻灯片时检测到它,并且仅在mobilePage.js中的所有内容都运行后才加载homePage.js

我为长时间的阅读道歉,但我之前尝试稀释这个例子显然是惨遭失败......

更新:用户@vsenko完全正确地说我混淆了客户端编程和服务器端编程,所以如果你遇到与我相同的问题,请阅读更多内容

1 个答案:

答案 0 :(得分:1)

据我所知,您正在尝试直接在网页上加载具有NodeJS特定API(精确的RequireJS API)的.js文件。这不起作用,因为浏览器本身不实现它。要使用此API,您必须使用预处理器(Webpack,Browserify或其他)。

您的方法的其他明显问题是您假设可以使用看起来像NodeJS模块的东西在不同设备之间传输数据。但是,您无法通过网络直接或通过服务器在网络上传输数据。