我想通过使用关键字with"在 javascript 中使用命名空间,但 CoffeeScript 将此报告为保留关键字并拒绝编译有什么方法可以在 cs 中使用命名空间吗?
I'd like to use namespaces as one would in javascript by using the keyword "with", but CoffeeScript reports this as a reserved keyword and refuses to compile is there any way I could use namespaces in cs?
特别是,我想动态包含一个 CoffeeScript 文件(受信任的源),例如为数据库模式加载模型,但我希望包含的脚本能够访问本地命名空间.
In particular, I want to include a CoffeeScript file dynamically (trusted source), like loading models for a database schema, but I want the included script to have access to a local namespace.
这就是我想要做的.我正在建立一个 web 框架,将目录树映射到基于 express 和 mongoose 的应用程序.例如,有一个子目录models",其中包含一个文件user.coffee",其中包含如下代码:
Here's what I want to do. I am setting up a web framework that maps the directory tree to an application based on express and mongoose. For example, there's a sub-directory 'models' that contains a file 'user.coffee' with code like this inside:
name:
type: String
unique: on
profiles: [ Profile ]
其中 Profile
是一个位于名为 model
的本地对象中的类.加载用户模型时,我希望它访问位于我的本地模型存储中的模型类.
Whereby Profile
is a class that sits in a local object named model
. When the user model is being loaded, I wanted it to access the model classes that sit in my local model store.
我现在的解决方法是将 model.Profile
写入文件user.coffee".希望我的意思很清楚.
My work-around for now was to write model.Profile
into the file 'user.coffee'. Hope it is clear what I mean.
第二次编辑
这是我在不使用 with
的情况下是如何做到的:
Here's how I did it without using with
:
user.coffee
user.coffee
name:
type: String
unique: on
profiles: [ @profile ]
profile.coffee
profile.coffee
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
对我来说似乎是一个不错的解决方案.
Seems an okay solution to me.
CoffeeScript 的 Coco fork 支持 with
语法;请参阅 https://github.com/satyr/coco/wiki/additions.但是,该语法只是将 this
的值设置为块中的目标对象,而不是编译为有问题且已弃用的 with
关键字.
The Coco fork of CoffeeScript supports a with
syntax; see https://github.com/satyr/coco/wiki/additions. However, that syntax simply sets the value of this
to the target object in a block, rather than compiling to the problematic and deprecated with
keyword.
假设您想在 CoffeeScript 中模拟 Coco 的 with
语法.你会做这样的事情:
Let's say that you wanted to emulate Coco's with
syntax in CoffeeScript. You'd do something like this:
withObj = (obj, func) -> func.call obj
那么你可以写
withObj = (obj, func) -> func.call obj
withObj annoyingly.lengthy.obj.reference, ->
@foo = 'bar'
@bar = 'baz'
当然,在这种简单的情况下,最好使用 jQuery 或 Underscore 的 extend
之类的实用函数:
Of course, in such simple cases, it's better to use a utility function like jQuery or Underscore's extend
:
_.extend annoyingly.lengthy.obj.reference, foo: 'bar', bar: 'baz'
这篇关于咖啡脚本中的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!