Reputation: 17997
I use sails.js, I'm wondering baout the scope var and lifetime on a var declared into a sails contoller.
var user = {};
module.exports = {
index: function (req, res) {
user.connected = false;
return res.view({
user: user
});
},
member: function (req, res) {
user.connected = true;
return res.view('home/index', {
user: user
});
}
};
In first place I tried to set user
only in the member
function, but once I visited the /member webpage, the user was initialized with user.connected=true
and when I visited the /index page it was still connected. So I added the user.connected=false
into the index
function and it works like expected.
But I dont understand at all. From what I know, the user
is a local variable to the HomeController.js
script, it should be destroyed each time the file is loaded and reset to {}
at each call.
Actually, while I wrote the question, I thought about something...
Because I use a module.exports
, the functions index and member are loaded into the memory and the call are not done on the HomeController.js
script but on the module.exports
global object, and because user
is an object, he is referenced by "pointer" and it's not a copy but a reference inside each function, so when I made a change on it, it's changed everywhere the reference is used. it's like a global object inside a module, weird.
Am I right? Did I miss something? Do you have more advanced explanation about that? Thanks.
Upvotes: 0
Views: 271
Reputation: 17748
I'm not familiar with sails, but the problem you'll have here is that every request is going to write a user to that module variable and you'll get all sorts of confusion when handling concurrent requests. The standard way of keeping a variable over the duration of a request is to append it to the request object:
module.exports = {
index: function (req, res) {
if (!req.user) {
// You'll probably have resolved a user and appended it to req in an
// Earlier middleware.
req.user = {};
}
user.connected = false;
res.view({ user: req.user });
},
member: function (req, res) {
if (!req.user) {
req.user = {};
}
user.connected = true;
res.view('home/index', { user: req.user });
}
};
Upvotes: 1