Backbone路由本质

Backbone路由分为两个大块,Router以及History
用户在Router中定义相关规则,然后开启history.start进行路由监控,执行默认的回调
所以,Router本身除了定义路由规则,全部调用的是Backbone.history的方法
Backbone.History的主要关注点事实上是 popstate(hashChange)的回调checkUrl,无论我们触发navigate或者点击浏览器后退
皆是进入此入口,再回调至Router定义的回调,从而实现相关逻辑

•创建规则

 var App = Backbone.Router.extend({
routes: {
"": "index", // #index
"index": "index", // #index
"detail": "detail" // #detail
},
index: function () {
var index = new Index(this.interface); },
detail: function () {
var detail = new Detail(this.interface); },
initialize: function () { },
interface: {
forward: function (url) {
window.location.href = ('#' + url).replace(/^#+/, '#');
} }
});

•开启路由控制

Backbone.history.start();

Backbone.history源码分析

history构造函数

 var History = Backbone.History = function () {
this.handlers = [];
_.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};

history.start 函数

 start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true; // Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/'); // 老版本ie以及希望使用hashChange, 使用iframe实现
if (oldIE && this._wantsHashChange) {
var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">');
this.iframe = frame.hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
} // Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Backbone.$(window).on('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
Backbone.$(window).on('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
/* 取决于选择hash还是pushState
      如果使用 pushState,调用方法
Backbone.history.start({ pushState: true });
*/ // Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location; // Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled
// browser, but we're currently in a browser that doesn't support it...
if (!this._hasPushState && !this.atRoot()) {
this.fragment = this.getFragment(null, true);
this.location.replace(this.root + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true; // Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._hasPushState && this.atRoot() && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment);
} } if (!this.options.silent) return this.loadUrl();
}

统一入口 loadUrl

loadUrl: function (fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function (handler) { // handlers是routes定义的集合,实例化Router时导入
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
}

(六)backbone - API学习 - Backbone路由的更多相关文章

  1. (三)backbone - API学习 - v0.9.2 与 v1.1.2区别

    Backbone.View v0.9.2 中Backbone.View 可以导出对象的options属性, v1.1.2 中去掉该属性,通过如下代码 viewOptions = ['model', ' ...

  2. python 学习笔记十六 django深入学习一 路由系统,模板,admin,数据库操作

    django 请求流程图 django 路由系统 在django中我们可以通过定义urls,让不同的url路由到不同的处理函数 from . import views urlpatterns = [ ...

  3. 开始学习 Backbone

    [转]开始学习 Backbone 如何将模型-视图-控制器 (MVC) 架构引入 Ajax Web 应用程序 如何高效管理 Web 应用程序中的数目众多的 JavaScript 代码行是一个挑战.As ...

  4. 【转】Backbone.js学习笔记(一)

    文章转自: http://segmentfault.com/a/1190000002386651 基本概念 前言 昨天开始学Backbone.js,写篇笔记记录一下吧,一直对MVC模式挺好奇的,也对j ...

  5. backbone库学习-Router

    backbone库的结构http://www.cnblogs.com/nuysoft/archive/2012/03/19/2404274.html 本文的例子来自http://blog.csdn.n ...

  6. backbone库学习-model

    backbone库的结构: http://www.cnblogs.com/nuysoft/archive/2012/03/19/2404274.html 本文所有例子来自于http://blog.cs ...

  7. 【转】Backbone.js学习笔记(二)细说MVC

    文章转自: http://segmentfault.com/a/1190000002666658 对于初学backbone.js的同学可以先参考我这篇文章:Backbone.js学习笔记(一) Bac ...

  8. Backbone.js学习之一

    昨天一个我崇拜的朋友,徐飞送我一本名为<Backbone.js实战>书,让我心中狂喜,于是带着这份浓厚的兴趣,开始研究Backbone.js之路. 打开这本书的第一句话就很有哲理,“授人以 ...

  9. (一)backbone - API入门

    初探 backbone采用MVC模式,本身提供了模型.控制器和视图从而我们应用程序的骨架便形成. Backbone.js 唯一重度依赖 Underscore.js. 对于 RESTful , hist ...

随机推荐

  1. Asp.net Core 缓存 MemoryCache 和 Redis

    Asp.net Core 缓存 MemoryCache 和 Redis 目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitH ...

  2. JS操作css的float属性的特殊写法

    使用js操作css属性的写法是有一定的规律的: 1.对于没有中划线的css属性一般直接使用style.属性名即可. 如:obj.style.margin,obj.style.width,obj.sty ...

  3. 如何升级nodejs版本

    直接下载最新版安装即可,例如我本地的nodejs版本为: y@y:untitled$ node -v v0.10.33 当前node官网最新版本为:Current Version: v0.12.2 下 ...

  4. mongodb工具

    可视化管理工具 http://www.mongovue.com/ mongodb use case http://www.mongodb.org/about/applications/ mongodb ...

  5. 体验Lua

    想用之和NGINX结合,终结公司混乱的NGINX配置 玩起来先,感觉很精简,很实用哟. print("hello world") a={,} b=a print(a==b,a~=b ...

  6. Android系统提供了哪些东西,供我们可以开发出优秀的应用程序

    1. 四大组件Android系统四大组件分别是活动(Activity).服务(Service).广播接收器(Broadcast Receiver)和内容提供器(Content Provider).其中 ...

  7. 在QLabel上点击获得的效果

    一般说只在button中点击获得事件,作出相应的反应.而往往需要在QLabel上作出点击和触碰的效果. 我用qlabel做出了一个效果,当鼠标碰到label区域,label底下出现一条线,离开后线条消 ...

  8. mysql redo log

    mysql> show variables like '%innodb_log_file_size%'; +----------------------+-----------+ | Varia ...

  9. bzoj2821作诗

    http://www.lydsy.com/JudgeOnline/problem.php?id=2821 分块 我们把数列分成$\sqrt{N}$块 记$f[i][j]$表示第i块到第j块的答案,这个 ...

  10. Android中sharedPreference的简单使用

    public class MainActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super ...