How do you properly access the global context in Node.js? Building a jQuery Plugin with Node.js
I am trying to build a simple jQuery plugin with node.js. I need to be able to access the global context, which in the browser is the window object, but haven't figured out how yet.
Here's the setup:
1. /spec/spec_runner.js
//fake browser window
var jsdom = require('jsdom').jsdom,
sys = require('sys'),
window = jsdom().createWindow(),
coffee = require('coffee-script'),
jasmine = require('jasmine-node'),
underscore = require('underscore'),
exec = require('child_process').exec;
global.jQuery = require("jquery");
global.$ = global.jQuery;
global._ = underscore;
global.window = window;
var plugin = require("../lib/my-plugin.js");
global.Model = plugin.Model;
2. /lib/my-plugin.js
var Model = function() {
console.log(window.document);
}
Model.prototype.doSomething = function() {
console.log(window.document);
}
Problem is, that window
attribute is not correct. I can get it to work if I do this:
Model.prototype.doSomething = function() {
console.log(global.window.document);
}
...but that's a problem for when I'm running this in the browser.
How do I get it so I can write the plugin and test 开发者_StackOverflow中文版it using node.js, but it has no (or at least a standardized) reference to global
or exports
?
It's working fine for me in this simplified test case:
scope_test.js
var jsdom = require('jsdom').jsdom;
var window = jsdom().createWindow();
global.window = window;
var test = require('./plugin_test.js')
global.Model = new test.Model();
Model.doSomething();
plugin_test.js
exports.Model = Model;
function Model() {
console.log(window.document);
}
Model.prototype.doSomething = function() {
console.log(window.document);
}
Result:
$ node scope_test.js
{ _childNodes:
[ { _attributes: [Object],
_ownerDocument: [Circular],
_childNodes: [Object],
style: [Object],
_childrenList: [Object],
_childNodesList: [Object],
_nodeName: 'html',
_tagName: 'html',
_created: true,
....
{ _childNodes:
[ { _attributes: [Object],
_ownerDocument: [Circular],
_childNodes: [Object],
style: [Object],
_childrenList: [Object],
_childNodesList: [Object],
_nodeName: 'html',
_tagName: 'html',
_created: true,
精彩评论