我想像在 javascript 中那样使用关键字“with”来使用命名空间,但是 CoffeeScript 将此报告为保留关键字并拒绝编译,有什么方法可以在 cs 中使用命名空间吗?
特别是,我想动态包含 CoffeeScript 文件(受信任的源),例如加载数据库架构的模型,但我希望包含的脚本能够访问本地命名空间。
Edit:
这就是我想做的。我正在建立一个 Web 框架,将目录树映射到基于express和mongoose的应用程序。例如,有一个子目录“models”,其中包含一个文件“user.coffee”,其中的代码如下:
name:
type: String
unique: on
profiles: [ Profile ]
Whereby Profile
是一个位于名为的本地对象中的类model
。当加载用户模型时,我希望它访问位于本地模型存储中的模型类。
我现在的解决方法是写model.Profile
进入文件“user.coffee”。希望我的意思很清楚。
2nd Edit
这是我在不使用的情况下做到的with
:
用户.coffee
name:
type: String
unique: on
profiles: [ @profile ]
简介.咖啡
content: String
这是动态加载的方式:
for fm in fs.readdirSync "#{base}/models"
m = path.basename fm, '.coffee'
schema[m] = (()->
new Schema coffee.eval (
fs.readFileSync "#{base}/models/#{fm}", 'utf8'
), bare: on
).call model
mongoose.model m, schema[m]
model[m] = mongoose.model m
对我来说似乎是一个不错的解决方案。