• 大熊君学习html5系列之------History API(SPA单页应用的必备------重构完结版)


    一,开篇分析

    Hi,大家好!大熊君又和大家见面了,(*^__^*) 嘻嘻……,这系列文章主要是学习Html5相关的知识点,以学习API知识点为入口,由浅入深的引入实例,

    让大家一步一步的体会"h5"能够做什么,以及在实际项目中如何去合理的运用达到使用自如,完美驾驭O(∩_∩)O~,好了,废话不多说,直接进入今天的主题,

    今天主要讲的是对昨天文章中的代码进行重构,并且相应的美化了一下前台UI界面,如下图所示的效果:

      

      哈哈哈酷吧!继续让咱们做个简单的回顾:

      为了提高Web页面的响应速度,越来越多的开发者开始采用单页面结构(single-page application)的解决方案。所谓的单页面结构就是指多个页面间切换时,不刷新当前整个页面,更新页面展示数据,并且相应地改变地址栏中的url,以使用户可以分享这个url。

      如果你使用chrome或者firefox等浏览器访问"github.com、plus.google.com"等网站时,细心的你会发现页面之间的点击是通过ajax异步请求的,

    同时页面的URL发生了了改变。并且能够很好的支持浏览器前进和后退。是什么有这么强大的功能呢?恩,这就会说到HTML5里引用了新的API:

    “history.pushState”和“history.replaceState”

    二者之间的重要区别------"window.history.replaceState"和"window.history.pushState"类似,不同之处在于replaceState不会在window.history里新增历史记录点,其效果类似于window.location.replace(url),都是不会在历史记录点里新增一个记录点的。当你为了响应用户的某些操作,而要更新当前历史记录条目的状态对象或URL时,使用replaceState()方法会特别合适。

    (二),流程梳理

      页面首次载入,虽然我们访问的URL是"http://localhost:8888/bbSPA.html",但是,实际URL确是:

    "http://localhost:8888/bbSPA.html#shanghai",”history.replaceState“完成了初始化url切换工作,并且初始做了加载

    "shanghai.data"的数据工作,鼠标点击左边的任意一个菜单项,右侧内容是Ajax载入,并且页面的URL随之发生改变,例如,点击北京。

    此时,我们点击地址栏的后退按钮,又回到了上海,并且显示内容。原理很简单,就是通过监听”window.onpopstate“,达到了自由切换的作用。

    测试时注意事项:

      测试需要搭建一个web服务器,以http://host/的形式去访问才能生效,如果你在本地测试以file://这样的方式在浏览器打开,就会出现如下的问题:

     
    Uncaught SecurityError: A history state object with URL 'file:///C:/xxx/xxx/xxx/xxx.html' cannot be created in a document with origin 'null'.

      因为你要pushState的url与当前页面的url必须是同源的,而file://形式打开的页面是没有origin的,所以会报这个错误。

    (三),重构一下昨天的代码

      说明几点:

        (1),昨天的代码虽然功能是完成了,但是很松散需要通过类的方式进行有效的组织。

        (2),Api要粒度化,各负其责,通过“init”初始化方式进项合理的组织。

        (3),UI部分做了修改增强了体验和视觉感。

        (4),补充相关数据文件,例如:“beijing.data”,内容如下:

          

    {
    	"content" : "Hi,这里是北京(*^__^*) 嘻嘻……)!"
    }
    

      

      好了!!!以下是完整代码:

      1,html源码

        

     1 <body>    
     2     <div class="hd">bbSPA测试页面</div>
     3     <ul id="list" >
     4         <li><a href="#beijing">北京</a></li>
     5         <li><a href="#shanghai">上海</a></li>
     6         <li><a href="#shenzhen">深圳</a></li>
     7         <li><a href="#guangzhou">广州</a></li>
     8         <li><a href="#tianjin">天津</a></li>
     9     </ul>
    10     <div  id="content-main"></div>
    11 </body>

    ·2,css源码

      

     1 .hd {
     2     height:60px;
     3     line-height: 60px;
     4     color:#f8f8f8;
     5     font-family: "微软雅黑" ;
     6     font-size: 24px;
     7     text-align: center;
     8     background: #49b49b;
     9 }
    10 #list {
    11     border-bottom:2px solid #49b49b;
    12     height:32px;
    13     520px;
    14     list-style:none;
    15 }
    16 #list li {
    17     padding:0px;
    18     margin-left:10px;
    19     84px;
    20     height:32px;
    21     float : left;
    22 }
    23 #list li a {
    24     padding:0px;
    25     84px;
    26     height:32px;
    27     line-height: 32px;
    28     background: #49b49b;
    29     color:#fff;
    30     font-family: arial ;
    31     font-size: 13px;
    32     text-align: center;
    33     display:block;
    34     text-decoration:none;
    35 }
    36 #list li a:hover {
    37     background: #019875;
    38 }
    39 #content-main {
    40     556px;
    41     height:220px;
    42     border:2px solid #49b49b;
    43 }

    3,Js源码

      

    function bbSPA(elem){
    	this.elem = elem ;
    } ;
    var bbSPAProto = bbSPA.prototype ;
    bbSPAProto.getElem = function(){
    	return this.elem ;
    } ;
    bbSPAProto._getDefaultHash = function(){
    	return window.location.hash ;
    } ;
    bbSPAProto._getCurrentHash = function(){
    	return this.getElem().eq(1).attr("href") ;
    } ;
    bbSPAProto._parseHash = function(hash){
    	return hash.split("#")[1] ;
    } ;
    bbSPAProto._fnPopStateHandler = function(target){
    	var that = this ;
    	var elem = target || null ;
    	var query = this._getDefaultHash() ;
    	if(!query){
    		if(elem = this._getElemByIndex(1)){
    			this._addToHistory(elem.attr("href"),true) ;
    			this._fnPopStateHandler(elem) ;
    		}
    	}
    	else{
    		this.getElem().find("li a").each(function() {
    			if (!elem && $(this).attr("href") == query){
    				elem = $(this) ;
    			}
    		}) ;
    		if(!elem){
    			this._fnPopStateHandler(this._getElemByIndex(1)) ;
    		}else{			 
    			elem.trigger("click") ;
    		}	
    	}
    } ;
    bbSPAProto._showContent = function(action){
    	var that = this ;
    	this._loadContent(this._parseHash(action) + ".data").done(function(data){
    		that._renderContent(data["content"]) ;
    		that._addToHistory(action,false) ;
    	}).fail(function(){
    		throw new Error("load content error !") ;
    	}) ;	
    } ;
    bbSPAProto._loadContent = function(url){
    	return $.ajax({
    		url : url ,
    		dataType : "json"
    	}) ;
    } ;
    bbSPAProto._getElemByIndex = function(index){
    	return this.getElem().find("li a").eq(index) ;
    } ;
    bbSPAProto._renderContent = function(text){
    	this.getElem().next().text(text) ;
    } ;
    bbSPAProto._addToHistory = function(hash,noState){
    	var stateObj = {
    		hash : hash
    	} ;
    	if(noState){
    		window.history.replaceState(stateObj,"",hash) ;
    	}
    	else{
    		window.history.pushState(stateObj,"",hash) ;
    	}
    } ;
    bbSPAProto._isSupportH5History = function(){
    	return !!("pushState" in window.history) ;
    } ;
    bbSPAProto.init = function(){
    	var that = this ;
    	if(!this._isSupportH5History()){
    		throw new Error("Not Support H5 History API !") ;
    	}
    	this.getElem().on("click","a",function(){
    		that._showContent($(this).attr("href")) ;
    		return false ;
    	}) ;
    	window.addEventListener("popstate",function(){
    		that._fnPopStateHandler() ;
    	},false) ;
    	this._fnPopStateHandler() ;
    } ;
    

      

    (四),最后总结

      (1),理解History Api的使用方式以及具体实例中使用的目的是为了解决哪些问题。

      (2),两个核心Api的不同之处在哪。

      (3),想想重构后与之前有什么优势,以及是否可以进一步抽象出不同的类,比如“Router”,“History”

      (4),说几句:编程是思想层面的事,实现方式很多,关键是看问题的深度与角度,好了不罗嗦了!!!明天继续!

                  哈哈哈,本篇结束,未完待续,希望和大家多多交流够沟通,共同进步。。。。。。呼呼呼……(*^__^*)   

  • 相关阅读:
    原创:vsphere概念深入系列二:vSphere交换机命令行查看排错
    原创:vsphere概念深入系列一:关于vsphere虚拟交换机的端口的数量限制。
    SQL Server 2012安装step by step
    iCloud无法导入vCard问题。fix the error when import vcard/vcf to icloud.
    微软补丁安装工具wusa报错。
    windows server 2012 浏览器IE10无法下载。
    VMware vSphere ESX* 5.x iSCSI Boot with VLAN Support: Guide
    How to configure ESXi to boot via Software iSCSI?
    光纤通道
    不错的介绍:存储基础知识。
  • 原文地址:https://www.cnblogs.com/bigbearbb/p/4261017.html
Copyright © 2020-2023  润新知