Created
December 30, 2010 11:14
-
-
Save paulbjensen/759682 to your computer and use it in GitHub Desktop.
How I do global variables with CoffeeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app.coffee | |
fs = require 'fs' | |
express = require 'express' | |
tasty = require './tasty.js' | |
app = express.createServer() | |
md = require("node-markdown").Markdown | |
firstArticleData = '' | |
articleList = [] | |
fs.readdir 'articles', (err, files) -> | |
globals.articleList = files | |
fs.readFile 'articles/' + globals.articleList[0], (err,data) -> firstArticleData = md(new String(data)) | |
app.configure -> | |
app.use express.staticProvider(__dirname + '/public') | |
app.set 'view engine', 'jade' | |
app.get '/', (req,res) -> | |
res.render 'index', { locals: { article: firstArticleData, list: globals.articleList } } | |
app.get '/:year/:month/:day/:title', (req,res) -> | |
articleUrl = [req.params.year, req.params.month, req.params.day, req.params.title].join('-') | |
fs.readFile 'articles/' + articleUrl + '.markdown', (err,data) -> | |
res.render 'index', { locals: { article: md(new String(data)), list: globals.articleList } } | |
app.listen 3000 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tasty.js, where I define a global variables holder | |
globals = {}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Under Node, you don't have to define a
globals
yourself; you can use the built-inglobal
object. Once something is attached toglobal
, it's automatically in the global scope (the same way thatwindow.x
is accessible as justx
in a browser environment).Just remember that in order to set a global, you have to write, say,
global.articleList = []
; then you can get it asarticleList
. But if you wanted to replacearticleList
entirely, you'd have to writeglobal.articleList = whatever
; writingarticleList = whatever
would create a new variable with local scope.With that in mind, here's how I'd rewrite your code (and no more need for tasty.js):