html5单页面应用程序之历史记录控制

window.addEventListener("hashchange",function(){
	var hash = window.location.hash.replace("#","");
	var sp = hash.split("~");
	console.log("current router is ",sp,hash);
	var controller = sp[0] || "home";
	
	if(sp.length == 2){
		var params = sp[1];
		var t = params.split("&");
		console.log(t);
		var states = {};
		for(var i = 0 ; i < t.length ; i++){
			states[t[i].split("=")[0]] = t[i].split("=")[1] || "";
		}
	}
	KS.Router.navTo(controller,states,true);
},false);

 通过hashchange监听,并且在真正实现跳转的时候讲history存入即可

run:function(){
		var hash = window.location.hash.replace("#","");
		var sp = hash.split("~");
		console.log("current router is ",sp,hash);
		var controller = sp[0] || "home";
		
		if(sp.length == 2){
			var params = sp[1];
			var t = params.split("&");
			console.log(t);
			var states = {};
			for(var i = 0 ; i < t.length ; i++){
				states[t[i].split("=")[0]] = t[i].split("=")[1] || "";
			}
		}
		if(KS.Router.routers[controller]){
			var state = window.history.state;
			KS.Router.navTo(controller,state);
		}else{
			var defaultController = this.routers[KS.config.welcome];
			window.history.pushState(null,"home page","./");
			defaultController.run();
		}
	},
	navTo:function(controller,pageParam,replace){
		for(var i = 0 ; i < KS.events.length ; i++){
			KS.events[i].el.removeEventListener(KS.events[i].type,KS.events[i].name,false);
		}
		KS.cController = controller;
		var location = window.location;
		console.log("nav to "+controller,pageParam);
		var defaultController = this.routers[controller];
		console.log("routers is "+ controller);
		if(pageParam)
				pageParam['controller'] = controller;
		else 
			pageParam  = {controller:controller}
		
		if(controller != "play"){
		}else{
			KS.playParam = pageParam;
		}
		//KS.resetNav(controller);
		defaultController.run();
	}

相关推荐