define(['underscorish', './user'], function (_, User) {
var Brain = (function() {
Defining brains and their dependencies
define(['underscorish', './user'], function (_, User) {
var Brain = (function() {
new Brain(robot)
Represents somewhat persistent storage for the robot.
robot - A Robot instance.
Returns a new Brain with no external storage or restore it from a local backup if present.
function Brain(robot) {
this.robot = robot;
this.data = {
users: {},
_private: {}
};
if (this.hasBackup())
this.data = this.hasBackup();
}
brain.set(key, value)
Public: Public: Store key-value pair under the private namespace.
Returns the instance.
Brain.prototype.set = function(key, value) {
this.data._private[key] = value;
this.save();
return this;
};
brain.get(key)
Public: Get value by key from the private namespace.
Returns the value or null if no value is found.
Brain.prototype.get = function(key) {
var value;
return ( value = this.data._private[key] ) != null ? value : null;
};
brain.delete(key)
Public: Remove value by key from the private namespace, if it exists.
Returns the instance.
Brain.prototype.delete = function(key) {
var value;
if (value = this.data._private[key])
delete this.data._private[key];
this.save();
return this;
};
brain.close()
Public: _Manage shutdown of the brain, Backup by save on localstorage the whole brain content
Returns the backup data.
Brain.prototype.close = function() {
this.backup();
return JSON.parse(localStorage.getItem('data'));
};
brain.users()
Public: Get an Array of User objects stored in the brain.
Returns an Array of User objects.
Brain.prototype.users = function() {
var names = _.map(this.data.users, function(user){
return user.name;
});
return names;
};
brain.userForName(name)
Public: Get a User object given a name. If it doesn’t exist create a new one.
Returns a User instance for the user with the specified name.
Brain.prototype.userForName = function(name) {
var user = this.data.users[name];
if (!user) {
user = new User(name, { 'history' : [] });
this.data.users[name] = user;
}
this.save();
return user;
};
brain.save()
or brain.backup()
Public: ‘save’ brain data to localstorate so that ‘brain’ scripts can handle persisting.
Returns nothing
Brain.prototype.save = Brain.prototype.backup = function(){
localStorage.setItem('data', JSON.stringify(this.data));
};
brain.hasBackup()
Public: check if a backup is present on the localstorage.
Returns the backup data.
Brain.prototype.hasBackup = function(){
var backup = JSON.parse(localStorage.getItem('data'));
if (backup != null)
if (backup.hasOwnProperty('_private') != null || backup.hasOwnProperty('users') != null)
return backup;
else
return false;
};
Brain.prototype.clearBackup = function(){
localStorage.clear();
};
return Brain
})();
return Brain;
});