(六)backbone - API學習 - Backbone路由

來源:互聯網
上載者:User

標籤:

Backbone路由本質

Backbone路由分為兩個大塊,Router以及History
使用者在Router中定義相關規則,然後開啟history.start進行路由監控,執行預設的回調
所以,Router本身除了定義路由規則,全部調用的是Backbone.history的方法
Backbone.History的主要關注點事實上是 popstate(hashChange)的回調checkUrl,無論我們觸發navigate或者點擊瀏覽器後退
皆是進入此入口,再回調至Router定義的回調,從而實現相關邏輯

 

•建立規則

 1 var App = Backbone.Router.extend({ 2     routes: { 3       "": "index",    // #index 4       "index": "index",    // #index 5       "detail": "detail"    // #detail 6     }, 7     index: function () { 8       var index = new Index(this.interface); 9   10    },11    detail: function () {12      var detail = new Detail(this.interface);13  14    },15    initialize: function () {16  17    },18    interface: {19      forward: function (url) {20        window.location.href = (‘#‘ + url).replace(/^#+/, ‘#‘);21      }22  23    }24 });

•開啟路由控制

Backbone.history.start();
Backbone.history源碼分析

history建構函式

 1 var History = Backbone.History = function () { 2   this.handlers = []; 3   _.bindAll(this, ‘checkUrl‘); 4  5   // Ensure that `History` can be used outside of the browser. 6   if (typeof window !== ‘undefined‘) { 7     this.location = window.location; 8     this.history = window.history; 9   }10 };

history.start 函數

 1 start: function(options) { 2       if (History.started) throw new Error("Backbone.history has already been started"); 3       History.started = true; 4  5       // Figure out the initial configuration. Do we need an iframe? 6       // Is pushState desired ... is it available? 7       this.options          = _.extend({root: ‘/‘}, this.options, options); 8       this.root             = this.options.root; 9       this._wantsHashChange = this.options.hashChange !== false;10       this._wantsPushState  = !!this.options.pushState;11       this._hasPushState    = !!(this.options.pushState && this.history && this.history.pushState);12       var fragment          = this.getFragment();13       var docMode           = document.documentMode;14       var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));15 16       // Normalize root to always include a leading and trailing slash.17       this.root = (‘/‘ + this.root + ‘/‘).replace(rootStripper, ‘/‘);18 19       // 老版本ie以及希望使用hashChange, 使用iframe實現20       if (oldIE && this._wantsHashChange) {21         var frame = Backbone.$(‘<iframe src="javascript:0" tabindex="-1">‘);22         this.iframe = frame.hide().appendTo(‘body‘)[0].contentWindow;23         this.navigate(fragment);24       }25       26       // Depending on whether we‘re using pushState or hashes, and whether27       // ‘onhashchange‘ is supported, determine how we check the URL state.28       if (this._hasPushState) {29         Backbone.$(window).on(‘popstate‘, this.checkUrl);30       } else if (this._wantsHashChange && (‘onhashchange‘ in window) && !oldIE) {31         Backbone.$(window).on(‘hashchange‘, this.checkUrl);32       } else if (this._wantsHashChange) {33         this._checkUrlInterval = setInterval(this.checkUrl, this.interval);34       }   
/* 取決於選擇hash還是pushState
      如果使用 pushState,調用方法
Backbone.history.start({ pushState: true });
*/35 36 // Determine if we need to change the base url, for a pushState link37 // opened by a non-pushState browser.38 this.fragment = fragment;39 var loc = this.location;40 41 // Transition from hashChange to pushState or vice versa if both are42 // requested.43 if (this._wantsHashChange && this._wantsPushState) {44 45 // If we‘ve started off with a route from a `pushState`-enabled46 // browser, but we‘re currently in a browser that doesn‘t support it...47 if (!this._hasPushState && !this.atRoot()) {48 this.fragment = this.getFragment(null, true);49 this.location.replace(this.root + ‘#‘ + this.fragment);50 // Return immediately as browser will do redirect to new url51 return true;52 53 // Or if we‘ve started out with a hash-based route, but we‘re currently54 // in a browser where it could be `pushState`-based instead...55 } else if (this._hasPushState && this.atRoot() && loc.hash) {56 this.fragment = this.getHash().replace(routeStripper, ‘‘);57 this.history.replaceState({}, document.title, this.root + this.fragment);58 }59 60 }61 62 if (!this.options.silent) return this.loadUrl();63 }

統一入口 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路由

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.