14
14

More than 5 years have passed since last update.

pushState未サポート時にhash fragmentを使わない設定

Last updated at Posted at 2012-07-21

backbone.js のデフォルトでは、pushState未サポート時は、 /hash fragment を付与した動作となるため画面遷移を伴うWebアプリと相性が悪い。

window.App =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  init: (options)->
    options = {} unless options
    options.pushState = true
    options.hashChange = false # don't want to rewrite /pathname to #pathname

    # override getHash
    # this can fire backbone router when url doesn't has hash fragment
    Backbone.history.getHash = ->
      if window.location.search
        search = window.location.search
      else
        search = ''
      return window.location.pathname
    if Backbone.history && !Backbone.History.started
      Backbone.history.start(options)
window.App = {
  Models: {},
  Collections: {},
  Views: {},
  Routers: {},
  init: function(options) {
    if (!options) {
      options = {};
    }
    options.pushState = true;
    options.hashChange = false;
    Backbone.history.getHash = function() {
      var search;
      if (window.location.search) {
        search = window.location.search;
      } else {
        search = '';
      }
      return window.location.pathname;
    };
    if (Backbone.history && !Backbone.History.started) {
      return Backbone.history.start(options);
    }
  }
};

options.hashChange = false によって、Hash Fragmentでの遷移を行わなくなる。しかしこのままだと、Routerのfireが動かなくなってしまうので、 Backbone.history.getHash をoverrideする。

backbone.jsを、JavaScript Url DispatcherとかRouterについて調べたにあるような使い方でも使えるようになる。

gist:pushState未サポート時にfragment hashを使わない設定

14
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14