[转帖]Mootools源码分析-43 -- Hash.Cookie

原帖地址:http://space.flash8.net/space/?uid-18713-action-viewspace-itemid-409100

原作者:我佛山人

 

代码
//以哈希表形式操作的Cookie类
//
因为Cookie的形式是字符串形式的键值对,所以可以跟哈希表数据相互转化

Hash.Cookie 
= new Class({
    
//继承自Cookie类
    Extends: Cookie,
    options: {
        
//是否自动保存,为true时每次修改哈希表数据都会自动更新Cookie
        autoSave: true
    },
    
//构造函数
    initialize: function(name, options)    {
        
//调用父类的构造函数,传递相同的参数
        this.parent(name, options);
        
//读取Cookie并解释为哈希表对象
        this.load();
    },

    
//保存Cookie
    save: function()    {
        
//先将哈希数据转为字符串
        var value = JSON.encode(this.hash);
        
//如果为空或者数据大小超过4K(Cookie的最大容量),取消保存
        if (!value || value.length > 4096)    return false//cookie would be truncated!
        //如果哈希表中没有数据,删除Cookie
        if (value == '{}')    this.dispose();
        
//否则保存Cookie
        else    this.write(value);
        
return true;
    },

    
//加载Cookie
    load: function()    {
        
//使用父类Cookie的read方法读取指定Cookie,再使用JSON.decode解释为哈希表数据
        this.hash = new Hash(JSON.decode(this.read(), true));
        
return this;
    }
});

//为Hash.Cookie添加扩展实现(主要是针对autoSave参数的实现)
//
原理是接管Hash的所有原型方法,加上包装,如果指定autoSave参数为true
//
每次调用的时候自动调用save方法保存
Hash.Cookie.implement((function()    {
    
var methods = {};
    
//遍历Hash原型中的方法
    Hash.each(Hash.prototype, function(method, name)    {
        methods[name] 
= function()    {
            
//因为原型中没有属性,所以这里能保证method都是方法,都具有apply方法
            //这时方法中的this指向Hash.Cookie实例的hash属性
            var value = method.apply(this.hash, arguments);
            
//如果指定自动保存,则在每个跟Hash有关的方法调用时都会自动保存
            if (this.options.autoSave)    this.save();
            
//返回用于扩展实现的对象
            return methods;
        };
    });
    
return methods;
})()); 

 

posted @ 2009-12-01 19:14  webgis松鼠  阅读(192)  评论(0编辑  收藏  举报