• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 63
  • Last Modified:

Accessing variable declared in one javascript file from another..

Hi,
I have the following structure of my javascript files... I am using webpack as the module bundler :

sidebar.js
-------------------
var ring = require('./ring.js');

$(document).ready(function() {
    var prod = $('#data').data();
    ring.setIsProd(prod);
});
-------------
ring.js
-------------
var filter = require('./filter.js');
var prod;
exports.setIsProd = function(prod) {
  this.prod = prod;
}
-------------
filter.js
-------------
Now in this file how do i access the value of prod ??
I tried using this.prod but didnt work.


Also I have some more variables that i want to set in ring...
like ring.setUserID(userID);

so i tried making one more function
exports.setUserId = function(userId) {
    this.userId = userId;
}

in ring.js same as isProd...
Any suggestions for an alternate way to do this ?
As if the number of such properties increase it looks really unclean to have so many exports

The idea behind the code is the ring.js file is a library which any user will be including inside its own js file which in this case is sidebar.js...  and apart from other work one major job is to include a filter in user page... so i separated this functionality into filter.js
But user can only interact with ring.js...and depending on prod value the filter will return a filter containing either prod entries or staging entries... So it needs the prod value..

Thanks
0
Rohit Bajaj
Asked:
Rohit Bajaj
1 Solution
 
Julian HansenCommented:
One option is to have your variables in an object and a generic get function

var data = {
  prod: 'value1',
  something: 'value2',
...
}
exports.getVar = function(id) {
   var ret = data[id] || false;
   return ret;
}

Open in new window


EDIT: Changed bad choice of parameter name 'var' for 'id'
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now