What I'm trying to do here is access the context
property (or context.settings
, more specifically) from within the ready
function in the same object. I'm not sure what the correct syntax is to do this.
here's the code:
module.exports = {
context: {
settings: require('./settings')
},
listen: function(callback) {
listen(context.settings.http.port);
callback(null);
},
ready: function (err) {
if (err)
{
throw err;
}
console.log("Ready and listening at http://localhost:" + context.settings.http.port);
}
};
just for clarification, I'm referring to the line console.log("Ready and listening at http://localhost:" + context.settings.http.port);
Edit: a bit more context (ha)
I did try this.context.settings.http.port
, but I get
TypeError: Cannot read property 'settings' of undefined
.
Here's the contents of settings.js
, just to be sure...
module.exports = {
db: {
host: '127.0.0.1',
port: 27017,
name: 'jsblogdemo'
},
http: {
port: 3000
}
};
Thanks!
Another possibility is this:
module.exports = (function() {
var context = {
settings: require('./settings')
},
listen = function(callback) {
listen(context.settings.http.port);
callback(null);
},
ready = function (err) {
if (err)
{
throw err;
}
console.log("Ready and listening at http://localhost:" +
context.settings.http.port);
};
return {
// context: context, // needed?
listen: listen,
ready: ready
};
}());
Then the functions have local access to the context
object without any worries about how they're called. And the context
object can be kept entirely private if you like.
If it's a single, static object, you could just do:
module.exports.context.settings
If you want a permanently bound this
, use .bind()
.
module.exports = {
context: {
settings: require('./settings')
}
}
module.exports.listen = function(callback) {
listen(this.context.settings.http.port);
callback(null);
}.bind(module.exports);
module.exports.ready = function (err) {
if (err) {
throw err;
}
console.log("Ready and listening at http://localhost:" + this.context.settings.http.port);
}.bind(module.exports);
As long as a method isn't being bound to another context by call
or apply
, this
refers to the current object context. For instance, use:
console.log(this.context.settings.http.port);
To print the listening port.