简体   繁体   English

在加载到 Meteor 的 javascript 文件之间共享全局变量

[英]Sharing global variables between javascript files loaded to Meteor

I have a javascript file that I place in the client/lib folder within my Meteor app.我有一个 javascript 文件,放在我的 Meteor 应用程序的 client/lib 文件夹中。 As the file grew bigger, I decided to split it into 3 files and define an object 'App' in the global namespace in order for the 3 files to share the data.随着文件越来越大,我决定将其拆分为 3 个文件并在全局命名空间中定义一个对象“App”,以便这 3 个文件共享数据。

Each file starts with每个文件以

var app = app || {};

(function () {
    'use strict';

    app.object1 = {

This way, file2 and file3 can still use app.object1, and so on.这样,file2 和file3 仍然可以使用app.object1,依此类推。

The problem is when Meteor loads the files, it seems to automatically wraps it with function(){}, and this makes app.object1 not accessible from files loaded subsequently.问题是当 Meteor 加载文件时,它似乎自动用 function(){} 包装它,这使得 app.object1 无法从随后加载的文件中访问。

(function(){
    var app = app || {};

   (function () {
   'use strict';

    app.object1 = {

What is the best way to avoid this issue?避免此问题的最佳方法是什么? Thanks.谢谢。

EDIT: I referred to this posting [Link:][1] Global variables in Meteor which suggests defining the variable without "var".编辑:我提到了这篇文章 [链接:][1] 流星中的全局变量,它建议定义没有“var”的变量。 I replaced the code in file1 to app = {}, but my app is now crashing in file2 in the following line of code, with the message from the Meteor console pasted below.我将 file1 中的代码替换为 app = {},但我的应用程序现在在以下代码行中的 file2 中崩溃,下面粘贴了来自 Meteor 控制台的消息。

app.ALL_LIST = 'all'

=> Your application is crashing. => 您的应用程序崩溃了。 Waiting for file change.等待文件更改。 ReferenceError: app is not defined参考错误:应用程序未定义

在您的变量声明中省略var ;) 然后它将在全局范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM