2014-09-23 79 views
3

我想创建一个使用集合的包。在正常的应用程序中,相同的代码工作正常,没有任何问题。在流星包中正确使用集合?

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未在服务器和客户端上定义。

回答

4

一旦您使用api.export,包中定义的对象可以在您的应用程序中引用。

你的情况:

api.export('TestCol',['server','client']); 

上面一行将暴露TestCol为全局变量,它会从你的应用入店。