Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables from another CoffeeScript file?

What is best practice to get a variable outside of its anonymous function without polluting the global namespace?

like image 821
fancy Avatar asked Jul 04 '11 03:07

fancy


1 Answers

A number of possibilities:

  • Create a properly name-scoped public accessor function to obtain the value upon demand.
  • Pass the value to the functions where it will be needed
  • Pass a private accessor function to the other module
  • Put the variable in a properly name-scoped global
  • Pass a "data object" to the other module that has the value in it (along with other values)

Which makes the most sense depends upon how much data you need to share, how widely it needs to be shared, whether the sharing is both ways, etc...

The typical design pattern for exposing global data with the minimum impact on polluting the global namespace is to do something like this:

var JF = JF || {};  // create single global object (if it doesn't already exist)
JF.getMyData = function() {return(xxx);};   // define accessor function
JF.myPublicData = ...;

Then, anywhere in your app, you can call JF.getMyData(); or access JF.myPublicData.

The idea here is that all public methods (or even data objects) can be hung off the JF object so there's only one new item in the global space. Everything else is inside that one object.

like image 179
jfriend00 Avatar answered Nov 15 '22 21:11

jfriend00