SPA-3~shell控制器下锚已经应用状态管理

单页应用因为是用javascript来生成HTML,所以我们把所有的外部脚本放在head区块中,以便改进组织结构和易读性。
一般在一个单独的html文件中开发功能容器的HTML和CSS。只有把容器调整为我们喜欢的那样之后,才把代码移至shell的css和javascript文件。

1.当发生历史事件的时候,更改锚,同时更改程序状态。
spa.shell=(function(){
    //------BEGIN MUDULE SCOPE VARIABLES------
    //静态配置值放在configMap变量中
    var 
        configMap={
            //缩紧html字符,这样有利于理解和维护
            main_html:String()
                //嵌入logo,账户设置和head容器中的搜索框
                +'<div class="spa-shell-head">'
                    +'<div class="spa-shell-head-logo"></div>'
                    +'<div class="spa-shell-head-acct"></div>'
                    +'<div class="spa-shell-head-search"></div>'
                +'</div>'
                //将导航(nav)和content容器放在主容器里面
                +'<div class="spa-shell-main">'
                    +'<div class="spa-shell-main-nav"></div>'
                    +'<div class="spa-shell-main-content"></div>'
                +'</div>'
                //创建footer容器
                +'<div class="spa-shell-foot"></div>'
                //将chat容器固定在外部容器的右下角
                +'<div class="spa-shell-chat"></div>'
                //创建modal容器,漂浮在其它内容的上面
                +'<div class="spa-shell-modal"></div>',
            chat_extend_time:1000,
            chat_retract_time:300,
            chat_extend_height:450,
            chat_retract_height:15,
            chat_extended_title:'click to retract',
            chat_retracted_title:'click to extend'
        },
        //将在整个模块中共享的动态信息放在stateMap变量中
        stateMap={
            $container:null,
            is_chat_retracted:true
        },
        //将jQuery集合缓存在jqueryMap中
        jqueryMap={},
        //声明所有模块作用域的变量,很多都是在之后赋值
        setJqueryMap,initModule,toggleChat,onClickChat;
    //------END MODULE SCOPE VARIABLES
    
    //------BEGIN UTILITY METHODS
    //unility Method 保留区块,这些函数不和页面元素交互
    //------END UTILITY METHODS------

    //------BEGIN DOM METHODS------
    //begin DOM method /setJqueryMap/
    //将创建和操作页面元素的函数放在“DOM Method”区块中
    //使用setJqueryMap来缓存jQuery集合。几乎编写的每个shell和功能模块都应该有这个函数
    //用途是可以大大地减少jQuery对文档的遍历次数,能够提高性能.
    setJqueryMap=function(){
        var $container=stateMap.$container;
        jqueryMap={
            $container:$container,
            $chat:$container.find('.spa-shell-chat')
        };
    };
    //end DOM mothod /setJqueryMap/
    
    //begin DOM method /toggleChat/
    //Purpose  :Extends or retracts chat slider
    //Arguments:
    //  *do_extend - if true,extends slider;if false retracts
    //  *callback - optional function to execute at end of animation
    //Settings
    //  *chat_extend_time,chat_retract_time
    //  *chat_extend_height,chat_retract_height
    //Returns : boolean
    //  *true - slider animation activated
    //  *false - slider animation not activated
    //State : sets stateMap.is_chat_retracted
    //  *true - slider is retracted
    //  *false - slider is extended 
    toggleChat=function(do_extend,callback){
        var 
            px_chat_ht=jqueryMap.$chat.height(),
            is_open=px_chat_ht===configMap.chat_extend_height,
            is_closed=px_chat_ht===configMap.chat_retract_height;
            is_sliding=!is_open&&!is_closed;
        //avoid race condition
        if(is_sliding){return false;}

        //begin extend chat slider
        if(do_extend){
            jqueryMap.$chat.animate(
                {height:configMap.chat_extend_height},
                configMap.chat_extend_time,
                function(){
                    jqueryMap.$chat.attr(
                        'title',configMap.chat_extended_title
                    );
                    stateMap.is_chat_retracted=false;
                    if(callback){callback(jqueryMap.$chat);}
                }
            );
            return true;
        }
        //End extend chat slider

        //begin restract chat slider
        jqueryMap.$chat.animate(
            {height:configMap.chat_retract_height},
            configMap.chat_retract_time,
            function(){
                jqueryMap.$chat.attr(
                        'title',configMap.chat_retracted_title
                    );
                stateMap.is_chat_retracted=true;
                if(callback){callback(jqueryMap.$chat);}
            }
        );
        return true
        //end retract chat slider
    }
    //End Dom mothod /toggleChat/
    //------END DOM METHODS------

    //------BEGIN EVENT HANDLERS------
    //为jquery事件处理函数保留的“Event Handlers”区块
    onClickChat=function(event){
        if(toggleChat(stateMap.is_chat_retracted)){
            $.uriAnchor.setAnchor({
                chat:(stateMap.is_chat_retracted?'open':'closed')
            });
        }
        toggleChat(stateMap.is_chat_retracted);
        return false;
    }
    //------END EVENT HANDLERS------

    //------BEGIN PUBLIC METHODS------
    //将公开的方法放在public method 区块中
    //begin public method /initModule/
    //创建initModule公开方法,用于初始化模块
    initModule=function($container){
        //load HTML and map jQuery collections
        stateMap.$container=$container;
        $container.html(configMap.main_html);
        setJqueryMap();

        //initialize chat slider and bind click handler
        stateMap.is_chat_retracted=true;
        jqueryMap.$chat
            .attr('title',configMap.chat_retracted_title)
            .click(onClickChat);
    }
    //end public method /initModule/

    //显式地导出公开方法,以映射(map)的形式返回。目前可用的只有initModule
    return {initModule:initModule};
    //------END PUBLIC METHODS------
}());

我们需要确保,当锚变化的时候,只改变应用需要改变的地方。这会使应用快很多,当部分页面内容没必要清除和重新渲染时,避免了发生烦人的“闪烁”现象。

2.使用锚来驱动应用状态

jquery.urianchor

我们希望的是始终让锚组件来驱动应用状态:
1.当发生历史事件时,更改URI的锚组件,以便体现更改的状态
--接收事件的处理程序调用shell的工具方法来改变锚
--然后事件处理程序退出
2.Shell的hashchange事件处理程序注意到了URI的变化并按它行事。
--将当前状态和新的锚表示的状态做比较
--根据比较确定的结果,尝试更改需要更改的应用部分
--如果不能处理请求的变化,则保持当前的状态,并恢复锚,以便和状态匹配。

spa.shell=(function($){
    //------BEGIN MODULE SCOPE VARIABLE------
    var 
        configMap={
            anchor_schema_map:{
                chat:{open:true,closed:true}
            },
            //缩紧html字符,这样有利于理解和维护
            main_html:String()
                //嵌入logo,账户设置和head容器中的搜索框
                +'<div class="spa-shell-head">'
                    +'<div class="spa-shell-head-logo"></div>'
                    +'<div class="spa-shell-head-acct"></div>'
                    +'<div class="spa-shell-head-search"></div>'
                +'</div>'
                //将导航(nav)和content容器放在主容器里面
                +'<div class="spa-shell-main">'
                    +'<div class="spa-shell-main-nav"></div>'
                    +'<div class="spa-shell-main-content"></div>'
                +'</div>'
                //创建footer容器
                +'<div class="spa-shell-foot"></div>'
                //将chat容器固定在外部容器的右下角
                +'<div class="spa-shell-chat"></div>'
                //创建modal容器,漂浮在其它内容的上面
                +'<div class="spa-shell-modal"></div>',
            chat_extend_time:1000,
            chat_retract_time:300,
            chat_extend_height:450,
            chat_retract_height:15,
            chat_extended_title:'click to retract',
            chat_retracted_title:'click to extend'
        },
        //将在整个模块中共享的动态信息放在stateMap变量中
        stateMap={
            $container:null,
            anchor_map:{},
            is_chat_retracted:true
        },
        //将jQuery集合缓存在jqueryMap中
        jqueryMap={},
        copyAnchorMap,setJqueryMap,toggleChat,
        changeAnchorPart,onHashchange,
        onClickChat,initModule;
        //------END MODULE SCOPE VARIABLES------

        //------BEGIN UTILITY METHODS------
        //Returns copy of stored anchor map;minimizes overhead(降低难度)
        copyAnchorMap=function(){
            return $.extend(true,{},stateMap.anchor_map);
        }
        //------END UTILITY METHODS------

        //------BEGIN DOM METHODS------
            //begin DOM method /setJqueryMap/
    //将创建和操作页面元素的函数放在“DOM Method”区块中
    //使用setJqueryMap来缓存jQuery集合。几乎编写的每个shell和功能模块都应该有这个函数
    //用途是可以大大地减少jQuery对文档的遍历次数,能够提高性能.
    setJqueryMap=function(){
        var $container=stateMap.$container;
        jqueryMap={
            $container:$container,
            $chat:$container.find('.spa-shell-chat')
        };
    };
    //end DOM mothod /setJqueryMap/
    
    //begin DOM method /toggleChat/
    //Purpose  :Extends or retracts chat slider
    //Arguments:
    //  *do_extend - if true,extends slider;if false retracts
    //  *callback - optional function to execute at end of animation
    //Settings
    //  *chat_extend_time,chat_retract_time
    //  *chat_extend_height,chat_retract_height
    //Returns : boolean
    //  *true - slider animation activated
    //  *false - slider animation not activated
    //State : sets stateMap.is_chat_retracted
    //  *true - slider is retracted
    //  *false - slider is extended 
    toggleChat=function(do_extend,callback){
        var 
            px_chat_ht=jqueryMap.$chat.height(),
            is_open=px_chat_ht===configMap.chat_extend_height,
            is_closed=px_chat_ht===configMap.chat_retract_height;
            is_sliding=!is_open&&!is_closed;
        //avoid race condition
        if(is_sliding){return false;}

        //begin extend chat slider
        if(do_extend){
            jqueryMap.$chat.animate(
                {height:configMap.chat_extend_height},
                configMap.chat_extend_time,
                function(){
                    jqueryMap.$chat.attr(
                        'title',configMap.chat_extended_title
                    );
                    stateMap.is_chat_retracted=false;
                    if(callback){callback(jqueryMap.$chat);}
                }
            );
            return true;
        }
        //End extend chat slider

        //begin restract chat slider
        jqueryMap.$chat.animate(
            {height:configMap.chat_retract_height},
            configMap.chat_retract_time,
            function(){
                jqueryMap.$chat.attr(
                        'title',configMap.chat_retracted_title
                    );
                stateMap.is_chat_retracted=true;
                if(callback){callback(jqueryMap.$chat);}
            }
        );
        return true
        //end retract chat slider
    }
    //End Dom mothod /toggleChat/

    //Begin DOM method /changeAnchorPart/
    //purpose : Changes part of the URI anchor component
    //Arguments:
    //  *arg_map - The map describing what part of the URI anchor we want changed
    //Returns : boolean 
    //  *true - the Anchor portion of the URI was update
    //  *false - the Anchor portion of the URI could not be updated
    //Action :
    //  The current anchor rep stored in stateMap.anchor_map.
    //  See uriAnchor for a discussion of encoding.
    //  This method
    //      *Creates a copy of this map using copyAnchorMap();
    //      *Modifies the key-values using arg_map.
    //      *Manages the distinction between independent and dependent values in the encoding
    //      *Attempts to change the URI using uriAnchor
    //      *Returns true on success , and false on failure.
    //
    changeAnchorPart=function(arg_map){
        var 
            anchor_map_revise=copyAnchorMap(),
            bool_return=true,
            key_name,key_name_dep;

        //Begin merge changes into anchor map
        KEYVAL:
        for(key_name in arg_map){
            if(arg_map.hasOwnProperty(key_name)){
                
                //skip dependent keys during iteration
                if(key_name.indexOf('_')===0){
                    continue KEYVAL;
                }
                // update independent key value
        anchor_map_revise[key_name] = arg_map[key_name];

                //update independent key values 
                key_name_dep="_"+key_name;
                if(arg_map[key_name_dep]){
                    anchor_map_revise[key_name_dep] = arg_map[key_name_dep]
                }else{
                    delete anchor_map_revise[key_name_dep]; 
                }
                                        delete anchor_map_revise['_s'+key_name_dep]
            }
        }
        //End merge changes into anchor map

        //Begin attempt to update URI ; revert if not successful 
        try{
            $.uriAnchor.setAnchor(anchor_map_revise);
        }
        catch(error){
            //replace URI with existing state
            $.uriAnchor.setAnchor(stateMap.anchor_map,null,true);
            bool_return=false;
        }
        //End attempt to update URI

        return bool_return;
    };
    // End DOM method /changeAnchorPart/
    //------END DOM METHODS------
    
    //------BEGIN EVENT HANDLERS------
    //Begin Event handlers /onHashchange/
    //Arguments:
    //  *event - jQuery event object.
    //Settings:none 
    //Returns :false
    //Action:
    //  *Parses the URI anchor component
    //  *Compares proposed application state with current 
    //  *Adjust the application only where proposed state differs from existing
    //
    onHashchange=function(event){
        var 
            anchor_map_previous=copyAnchorMap(),
            anchor_map_proposed,
            _s_chat_previous,_s_chat_proposed,
            s_chat_proposed;

            //attempt to parse anchor,$.uriAnchor.makeAnchorMap() always produce a addition 
                        //key  '_s_'+key ,such as _s_chat
            try{anchor_map_proposed=$.uriAnchor.makeAnchorMap();}
            catch(error){
                $.uriAnchor.setAnchor(anchor_map_previous,null,true);
                return false;
            }
            stateMap.anchor_map=anchor_map_proposed;

            //convenience vars
            _s_chat_previous=anchor_map_previous._s_chat;
            _s_chat_proposed=anchor_map_proposed._s_chat;

            //Begin adjust chat component if changed 
            if(!anchor_map_previous||_s_chat_previous!==_s_chat_proposed){
                s_chat_proposed=anchor_map_proposed.chat;
                switch(s_chat_proposed){
                    case 'open' : 
                        toggleChat(true);
                    break;
                    case 'closed' :
                        toggleChat(false);
                    break;
                    default:
                        toggleChat(false);
                        delete anchor_map_proposed.chat;
                        $.uriAnchor.setAnchor(anchor_map_proposed,null,true);
                }
            }
            // End adjust chat component if changed
            return false;
    };
    //End Event handler /onHashchange/

    //Begin Event handler /onHashchange/
    onClickChat=function(event){
        changeAnchorPart({
            chat:(stateMap.is_chat_retracted?'open':'closed')
        });
        return false;
    }
    //End Event handler /onClickChat/
    //------END EVENT HANDLERS------

    //------BEGIN PUBLIC METHODS
    //Begin Public method /initModule/
    initModule=function($container){
        //load HTML and map jQuery collections
        stateMap.$container=$container;
        $container.html(configMap.main_html);
        setJqueryMap();

        //initialize chat slider and bind click handler
        stateMap.is_chat_retracted=true;
        jqueryMap.$chat
            .attr('title',configMap.chat_retracted_title)
            .click(onClickChat);

        // 配置uriAnchor插件,用于检测模式(schema)
        //configure uriAnchor to use our schema 
        $.uriAnchor.configModule({
            schema_map:configMap.anchor_schema_map
        });
        //Handler URI anchor change events
        //this is done /after/ all feature modules are configured
        //and initialized ,otherwise they will not be ready to handle
        //the trigger event ,which is used to ensure the anchor
        //is considered on-load
        //
        $(window)
            .bind('hashchange',onHashchange)
            .trigger('hashchange');
    };
    //End Public method /initModule/
    return {initModule:initModule};
    //------END PUBLIC METHODS------

}(jQuery));
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,264评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,549评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,389评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,616评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,461评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,351评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,776评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,414评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,722评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,760评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,537评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,381评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,787评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,030评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,304评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,734评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,943评论 2 336

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,517评论 18 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,331评论 0 17
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,680评论 6 342
  • 我在一家大型私营企业工作,工作很努力,经验也不错,能力足以应对这个岗位,但得不到领导的信任和支持,同样情况的另一个...
    明哥聊求职阅读 2,457评论 2 5
  • 总有一天你会发现我所做的一切都是有原因的。分别不代表以后都不再见面。随着时间的流逝,大一大二早就在我们不经意间一晃...
    Sunnyboy3w阅读 189评论 0 0