1、需求
由于项目一开始做的时候不甚完善,所有的网页没有路由功能,导致一些搜索结果在页面跳转之后,没有被记录下来,在页面跳转之后回退,得到的是页面最原始的结果,没有指定的搜索条件。最近项目的在完善这些小的细节,所以在此记录一下。
2、操作
由于项目的所有传参都是使用 '?' 来标识的,而Backbone的路由是使用锚点 '#' 来的,为了兼容以前的做法,不得不去修改Backbone的源码,还好路由部分的源码不多
2.1 修改Backbone的源码,版本1.3.3
1)修改标识 '#' -> '?'
把源代码中的字符串中的'#'修改为'?',把单个的'#'修改为'?'
例:var pathStripper = /#.*$/;修改为:var pathStripper = /?.*$/;例:this.location.replace(rootPath + '#' + this.getPath());修改为:this.location.replace(rootPath + '?' + this.getPath());注:字符串中的?需要来转义,字符不需要
2)修改锚点的路由设置
_updateHash: function(location, fragment, replace) {if (replace) {var href = location.href.replace(/( :|?).*$/, '');location.replace(href + '?' + fragment);} else {// Some browsers require that `hash` contains a leading #.// location.hash = '?' + fragment;var href = location.href.replace(/( :|?).*$/, '');// window.history.pushState({}, 0, href + '?' + fragment);window.history.replaceState({}, 0, href + '?' + fragment);}}注:
location.hash是原始的修改参数方法,会替换url中'#'以及后的所有内容
window.history.pushState可选目标方法,会增加一次历史记录,刷新页面
window.history.replaceState可选目标方法,会替换掉当前的页面记录,不刷新页面(目前选用方案)
2.2 写一个Util
写一个工具类用于Router的快速使用,和统一修改
/*** RouterUtil.js*/var RouterUtil = (function() {// Backbone Router with a custom parameter extractorvar Router = Backbone.Router.extend({params : "",routes : {"*actions": "defaultRoute" // 匹配 http://example.com/#anything-here},defaultRoute : function(params) {Router.params = params;},});var routerUtil = {web_router : null,init(){// 初始化if(!routerUtil.web_router){routerUtil.web_router = new Router;Backbone.history.start();}},getParam(cbFn){routerUtil.init();// 获取#之后的参数if(cbFn){cbFn(Router.params);}},route(returnUrl, cbFn){// 动态的调整 路由规则 例:topic/:pageno/:pagesizerouterUtil.web_router.route(returnUrl,"page", cbFn)},start(){// 启用路由if(!Backbone.History.started){Backbone.history.start();}},stop(){// 关闭路由if(Backbone.History.started){Backbone.history.stop();}},navigate(returnUrl){/*** 重构 ,路由导向*///此处根据自己的需求去构建参数拼接//returnUrl为'?'之后的内容if(returnUrl){}else{returnUrl = "searchType=" + SearchBoxUtil.searchType + "&" + SearchBoxUtil.formData;}routerUtil.web_router.navigate(returnUrl, {trigger: true});}}return routerUtil;})();2.3 使用
在js中引用的一些方法
// 页面的初始化initPagi : function(){RouterUtil.getParam(function(params){if(!params){params = "";}//处理参数...});},//查询函数queryData : function(returnUrl,isInitSearchBox){if(!returnUrl){returnUrl = "";}if(isInitSearchBox){//第一次初始化查询}else{//非第一次初始化查询RouterUtil.navigate(returnUrl);}...},遗失的拂晓菜鸟一枚,随便弄弄的一点代码,有更好的方案请赐教
继续阅读与本文标签相同的文章
上一篇 :
ctrl shift o失效
下一篇 :
mongo去重统计
-
Mysql中的Redo Log解析(一)
2026-05-26栏目: 教程
-
系统编程语言Rust特点介绍(1)
2026-05-26栏目: 教程
-
有关OPC UA over TSN的常见问题解答
2026-05-26栏目: 教程
-
类图画法?这样记
2026-05-26栏目: 教程
-
查询数据库里当前用户下的所有表的总共数据sql
2026-05-26栏目: 教程
