There are a number of ways to make a variable persistent across function calls. They all involve moving the variable declaration or storage outside of the scope of the function so that it doesn't get recreated and then die each time the function runs.
Property of the Function
One of the simpler ways is to just assign it as a property of the np_handler() function. This prevents any global namespace pollution or conflict, but makes it persist as long as the function that uses it exists. That can be done like this:
var np_handler = function (act) {
if (act.params.length === 0) {
UserModel.find({ nick: act.nick }, function (err, data) {
if (!data) {
np_handler.lfmuser = act.nick;
} else {
np_handler.lfmuser = data.lastfm;
}
});
} else {
UserModel.find({ nick: act.params[0] }, function (err, data) {
if (!data) {
np_handler.lfmuser = act.params[0];
} else {
np_handler.lfmuser = data.lastfm;
}
});
}
};
// initialize
np_handler.lfmuser = '';
Global Scope
If you wanted to put it into the same scope as the function, you can just declare it at the that same scope and not declare it locally like this, though if np_handler was in the global scope, you now have one more item in the global scope which you generally try to avoid as much as possible:
var lfmuser = '';
var np_handler = function (act) {
if (act.params.length === 0) {
UserModel.find({ nick: act.nick }, function (err, data) {
if (!data) {
lfmuser = act.nick;
} else {
lfmuser = data.lastfm;
}
});
} else {
UserModel.find({ nick: act.params[0] }, function (err, data) {
if (!data) {
lfmuser = act.params[0];
} else {
lfmuser = data.lastfm;
}
});
}
};
Global Namespace Object
If you need it to be globally accessible, but you don't want to pollute the global namespace any more than required or you want to avoid the possibility of a name conflict, you can create one global namespace object and make the global variable be a property of that object. You can then put all your globals as properties on the one master global object and only have introduced one new name in the global space rather than many. You would do that like this:
// make sure myGlobals is defined and assign a property to it
var myGlobals = myGlobals || {};
myGlobals.lfmuser = '';
var np_handler = function (act) {
if (act.params.length === 0) {
UserModel.find({ nick: act.nick }, function (err, data) {
if (!data) {
myGlobals.lfmuser = act.nick;
} else {
myGlobals.lfmuser = data.lastfm;
}
});
} else {
UserModel.find({ nick: act.params[0] }, function (err, data) {
if (!data) {
myGlobals.lfmuser = act.params[0];
} else {
myGlobals.lfmuser = data.lastfm;
}
});
}
};