不能使用CoffeeScript在meteor中创建仅用于客户端的集合

Can't create a client only collection in meteor using CoffeeScript

本文关键字:用于 客户端 集合 创建 CoffeeScript meteor 不能      更新时间:2023-09-26

嗨,我需要创建一个客户端集合,我使用CoffeeScript,我试图这样创建它:

Template.mcqQuestionOptionsFieldset.onCreated ->
  @AddMcqOptions = new Mongo.Collection null

当我运行应用程序时,它不工作,我得到错误:

ReferenceError: AddMcqOptions is not defined

我尝试了没有'@'符号我尝试了一切,在javascript控制台我看不到它是加载的,似乎集合不存在…

如果我删除@符号错误路径移动到其他文件,我试图使用变量,但如果我添加@错误路径出现在同一文件中,我声明的变量,有人能告诉我发生了什么?

谢谢

客户端集合不需要在模板中定义,特别是在其他文件中使用它时。

添加一个文件,例如client/collections.coffee:

@AddMcqOptions = new Mongo.Collection null

然后在客户端任何地方正常使用AddMcqOptions.insert(...)等。

如果您想保持当前的结构,也可以使用胖箭头(我还没有测试过)。您还将失去对引用模板的this/@的访问权。

Template.mcqQuestionOptionsFieldset.onCreated =>
  @AddMcqOptions = new Mongo.Collection null

另一个可能的选项,允许您正常使用this/@:

self = this
Template.mcqQuestionOptionsFieldset.onCreated ->
  self.AddMcqOptions = new Mongo.Collection null

如果你想要模板特定的客户端集合,你可以这样尝试。我是这样使用的,它工作得很好:

Template.myTemplate.created = function () {
    var instance = this;
    instance._MyClientCollection = new Mongo.Collection(null);
    instance._MyClientCollection.insert({...});
}
Template.myTemplate.helpers({
    options: function () {
        return Template.instance()._MyClientCollection.find({...}, {sort: {...}});
    }
});
Template.myTemplate.destroyed = function () {
    var instance = this;
    instance._MyClientCollection.remove({});
}