问题
So I am trying to get my head around the javascript AMD pattern using requireJS. My experience with JS is limited and no doubt this is what is hampering me. I would not be surprised if I am pointed in the direction of "JS for Dummies". If anyone can bear to help me with this I would be VERY grateful.
I have defined a module called "security" which has the following definition - cut down a bit.
define(['services/storage'], function(storage) {
var security = {
authToken: {},
loadAuthToken: loadAuthToken,
saveAuthToken: saveAuthToken,
};
return security;
function saveAuthToken(token) {
if (token) {
storage.save("DiffusrAuthToken", token);
security.authToken = token;
}
};
function loadAuthToken() {
if (security.authToken.expires) {
return security.authToken;
} else {
var token = storage.load("DiffusrAuthToken");
security.authToken = token;
return token;
}
};
})
Essentially I want to save the state of some values defined in the module, in the case above, the authToken. This is so that when other modules require this module I don't have to go to localStorage to get it. The only way I can get this to work is by defining a property of the return object, and setting this to an empty object initially. This does not seem satifactory, because I do not want to expose it directly to other modules as they could change it.
The non-AMD way would be to define an object in the global scope and attach properties to it. BUT, I thought the whole point of AMD was to avoid this.
Question: How, generally, should I set values in modules that can be accessed from other modules?
回答1:
Anything you don't export in a module cannot be accessed outside the module but is still available within the module closure. For example, you can create a var but never attach it as a property of the security export object. You can create specific accessor methods to the export object that can access this private variable only in a way that you want users of the module to, as you have done with your saveAuthToken and loadAuthToken methods.
define(['services/storage'], function(storage) {
var authToken; // private to security module
function saveAuthToken(token) {
if (token) {
storage.save("DiffusrAuthToken", token);
authToken = token; // store to private variable
}
};
function loadAuthToken() {
if (authToken.expires) {
return authToken;
} else {
var token = storage.load("DiffusrAuthToken");
authToken = token;
return token;
}
};
// export contains no reference to authToken
var security = {
loadAuthToken: loadAuthToken,
saveAuthToken: saveAuthToken,
};
return security;
});
来源:https://stackoverflow.com/questions/20058286/javascript-amd-pattern-confusion-persisting-property-values