我们可以通过查看Meteor的内部代码来获知Meteor运行时所带有的变量。
在meteor/app/server中,有server.js这个文件,里面有个run函数,是在Meteor运行时会被执行的。里面有声明到这些变量。
__meteor_bootstrap__ = {
// connect middleware
app: app,
// metadata about this bundle
bundle: bundle,
// function that takes a connect `req` object and returns a summary
// object with information about the request. See
// #BrowserIdentifcation
categorizeRequest: categorizeRequest,
// list of functions to be called to determine any attributes to be
// added to the '<html>' tag. Each function is passed a 'request'
// object (see #BrowserIdentifcation) and should return a string,
htmlAttributeHooks: [],
// Node.js 'require' object.
require: require,
// functions to be called after all packages are loaded and we are
// ready to serve HTTP.
startup_hooks: []
};
app变量的由来:
var connect = require('connect');
var app = connect.createServer();
connect模块可以查看meteor/lib/node_modules/connect/lib里的connect.js。这里可以更清楚的了解到connect的由来。其实它就是一个nodejs的HTTPServer。
connect.js:
var HTTPServer = require('./http').Server
, HTTPSServer = require('./https').Server;
function createServer() {
if ('object' == typeof arguments[0]) {
return new HTTPSServer(arguments[0], Array.prototype.slice.call(arguments, 1));
} else {
return new HTTPServer(Array.prototype.slice.call(arguments));
}
};
http.js:
var http = require('http');
var Server = exports.Server = function HTTPServer(middleware) {
this.stack = [];
middleware.forEach(function(fn){
this.use(fn);
}, this);
http.Server.call(this, this.handle);
};
https.js:
var HTTPServer = require('./http').Server
可以参考这里:http://www.infoq.com/cn/articles/nodejs-connect-module 介绍nodejs的connect模块。
可以使用app这个变量来实现Ajax。如:
var ROUTE = "/Ajax";
var fn = function(req, res) {
//.....
};
app = __meteor_bootstrap__.app;
app.stack.unshift ({route: ROUTE, handle: fn});
例如当ajax提交的url为http://localhost:3000/Ajax(or "/Ajax" work too),就会调用fn函数进行处理。至于这个过程怎么来,内容比较多,建议自己看源码。
bundle变量的由来:
// read bundle config file
var info_raw =
fs.readFileSync(path.join(bundle_dir, 'app.json'), 'utf8');
var info = JSON.parse(info_raw);
var bundle = {manifest: info.manifest, root: bundle_dir};
下面这个还涉及到server.js里的其他函数,最好自己去查看。
var categorizeRequest = function (req) {
return {
browser: identifyBrowser(req),
url: url.parse(req.url, true)
};
};