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. DOM 之通俗易懂讲解

    DOM是所有前端开发每天打交道的东西,但是随着jQuery等库的出现,大大简化了DOM操作,导致大家慢慢的“遗忘”了它的本来面貌.不过,要想深入学习前端知识,对DOM的了解是不可或缺的,所以本文力图系 ...

  2. 【转】关于FPGA中建立时间和保持时间的探讨

      时钟是整个电路最重要.最特殊的信号,系统内大部分器件的动作都是在时钟的跳变沿上进行, 这就要求时钟信号时延差要非常小, 否则就可能造成时序逻辑状态出错:因而明确FPGA设计中决定系统时钟的因素,尽 ...

  3. 转:Java反射教程

    原文来自于:http://www.importnew.com/9078.html 什么是反射?反射有什么用处? 1. 什么是反射? “反射(Reflection)能够让运行于JVM中的程序检测和修改运 ...

  4. DbUtility-第一次接触

    DbUtility这个以前就知道,可是由于底层是4.5的框架,我就一直没有仔细看过,最近自己的开发框架升级到了4.5,就开始学习这个组件. 总体来说,这个组件用起来非常简单.举例说明: await d ...

  5. WebService实现文件上传下载

    一:服务端:一个普通java web工程 package com.wzh.file; import com.sun.xml.ws.developer.StreamingAttachment; impo ...

  6. CA

    http://www.cmca.net/index.php?option=com_content&view=article&id=55&Itemid=16

  7. [LeetCode 109] - 将已排序链表转换为二叉搜索树 (Convert Sorted List to Binary Search Tree)

    问题 给出一个元素以递增序列排序的单链表,将其转换为一棵高度平衡的二叉搜索树. 初始思路 二叉搜索树高度平衡,意味着左右子树的高度要平衡.根据二叉树左子树节点小于根节点,右子树节点大于根节点的性质:我 ...

  8. 对类HelloWorld程序中添加一个MessageBox弹窗

    对类HelloWorld程序中添加一个MessageBox弹窗 分析: 任一程序运行的时候都会加载kernel32.dll的,但MessageBoxA()这个API却是在user32.dll中的.所以 ...

  9. Changing a Service's Configuration

    Changing a Service's Configuration   A service configuration program uses the ChangeServiceConfig an ...

  10. 浅析门户网站体育赛事CDN加速解决方案

    经过近些年来的高速发展,互联网已经成为现今媒体传播的主要力量.这一点在大型体育赛事的报道与转播上,体现的尤为明显.更及时的信息内容.更多样的报道形式.更齐全的资料组成.更方便的阅读查询.更具互动性的报 ...