问题描述
我正在尝试创建一个使用集合的包。在正常的应用程序中,同样的代码工作正常没有任何问题。
I am trying to create a package that uses a collection. In a normal application, the same code works fine without any issues.
collectiontest.js(软件包代码)
collectiontest.js (Package code)
// Why do I need to set the global property manually?
var globals = this || window;
TestCol = new Meteor.Collection('test');
globals.TestCol = TestCol;
console.log('defined');
if(Meteor.isServer){
Meteor.publish('test', function(){
return TestCol.find();
});
Meteor.startup(function(){
console.log('wtf');
TestCol.remove({});
TestCol.insert({test: 'a document'});
});
};
if(Meteor.isClient){
Meteor.subscribe('test');
};
在客户端和服务器上测试传递:
Test passes on client and server:
Tinytest.add('example', function (test) {
console.log('here');
var doc = TestCol.findOne();
test.equal(doc.test, 'a document');
console.log(doc);
});
但是如果我在客户端上打开开发人员工具并运行:
But if I open developer tools on the client and run:
TestCol.find().count()
结果是0.为什么?
此外,为什么我必须有 globals.TestCol = TestCol;
行才能运行测试?没有该行,在服务器和客户端上都不会出现错误:未定义TestCol。
The result is 0. Why?Also, why do I have to have the line globals.TestCol = TestCol;
for the tests to run at all? Without that line, an error: TestCol is not defined occurs on both the server and the client.
推荐答案
可以在您的应用程序中引用,一旦您使用。
Objects defined in a package can be referenced in your application once you use api.export
.
在您的情况下:
api.export('TestCol',['server','client']);
上述行会将 TestCol
并且可以从您的应用程序访问。
Above line will expose TestCol
as global variable and it will be accesible from your Application.
这篇关于正确使用流星包中的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!