我正在使用express 框架使用 postgresql开发node.js应用程序。我正在尝试尽可能多地遵循 MVC。
我想在模型类中生成查询结果,然后将它们传递给控制器类。该控制器类实际上是在路由中定义的,因此控制器类可以获取结果并将它们作为 http 响应传递。
这是我的数据库助手类,即模型类。我的问题出在课程最后的听众身上。
exports.DatabaseHelper = function()
{
var allVenues;
var client;
var customEventEmitter;
this.init = function()
{
this.customEventEmitter = new events.EventEmitter();
client = new pg.Client(
{
host:'localhost',
port:5432,
database:'postgres',
user:'postgres',
password:'password'
});
}
this.getVenuesWithEvents = function(searchParams)
{
allVenues = new Array();
var query_for_venues;
this.init();
client.connect();
client.addListener("error",function()
{
sys.puts("postgresql interface error");
});
query_for_venues = client.query("select id, name, location, latitude, longitude, category_generalized from venues");
query_for_venues.addListener("row",function(row)
{
//some code
});
query_for_venues.addListener("end",function(result)
{
this.customEventEmitter.emit("data",allVenues);
//////////////////////////////////////////////////////////
//this line shows error....'this' refers to the query object so customEventEmitter is undefined
//customEventEmitter is my idea of sharing the query results to my controller class.
//but I cannot do this becasue of this error
console.log("after emission");
});
}
}
如何从侦听器中访问 customEventEmitter 实例变量?