我正在尝试创建一个使用集合的包。在正常的应用程序中,相同的代码可以正常工作,没有任何问题。
collectiontest.js(封装代码)
// 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');
};
在客户端和服务器上测试通过:
Tinytest.add('example', function (test) {
console.log('here');
var doc = TestCol.findOne();
test.equal(doc.test, 'a document');
console.log(doc);
});
但是如果我在客户端打开开发者工具并运行:
TestCol.find().count()
结果是0,为什么?
另外,为什么我必须使用 globals.TestCol = TestCol;
行才能运行测试?如果没有该行,则会在服务器和客户端上出现错误:未定义 TestCol。
最佳答案
一旦您使用api.export
,就可以在您的应用程序中引用包中定义的对象.
在你的情况下:
api.export('TestCol',['server','client']);
上一行会将 TestCol
公开为全局变量,并且可以从您的应用程序访问它。
关于collections - 正确使用 meteor 包中的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25986354/