I ran into a problem, where I need to bind some variable to context of module. I have two folders : Controllers and Models. In models, I have a model like this :
exports = {
name: String,
password: String
}
and the Controller looks like this :
exports = {
onMessage: (message) {
Model.doSomething();
}
}
So I need to access the Model in the Controller while not require-ing it. I don't think loading the Model and giving it to global is good practice for this. I am looking for something like MyNodeJsModule.addVarToContext(Model);
The thing why I don't want to require model in controller is, I need the model to be loaded by external system and let the external system replace the Model by database-accessable model.
probably you have to change Controller like this?
module.exports = function(Model) {
return {
onMessage: function(message) {
Model.doSomething();
}
};
}
Not quite sure what you need exactly but you can export Controller as a constructor and then bind each instance to a specific model.
So, in controller:
// Constructor
var Controller = function(model){
this._model = model;
}
Controller.prototype.onMessage = function(message) {
this._model.doSomething(message);
};
Controller.prototype.setModel = function(newModel){
this._model = newModel;
}
exports.Controller = Controller;
Then (externally):
var ModelController = require('./controller').Controller;
var modelController1 = new ModelController(model1);
var modelController2 = new ModelController(model2);
modelController1.setModel(model2);
modelController2.setModel(model1);