location.hashを監視して、変更があった場合に、関数を呼び出す。おもにAjax向け、その2。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<title></title>

<style type="text/css">
p { margin-bottom: 300px; }
</style>

<body>
<p>
<a href="#a;dt=4;et=1">to a</a>
<a href="#a;dt=5;et=2">to b</a>
<a href="#c;dt=6;et=3">to c</a>
</p>
<p id="a">a</p>
<p id="b">b</p>
<p id="c">c</p>

<script type="text/javascript">

var HashManager = function ( interval, cbFunc, cbObj ) {

  var defInterval = 300;
  var timerId;
  var hash;
  var memory;
  

  //チェック中止
  this.stop = (function ( ) {
    return function ( ) {
      if( timerId ) {
        clearInterval( timerId );
        timerId = null;
      }
    };
  })();
  

  //チェック開始
  this.start = (function ( ) {
    return function ( ) {
      this.stop();
      return timerId = setInterval( (function( that ) {
        return function ( ) { that.check(); }; })( this ), interval );
    };
  })();
  

  //hashのチェック
  this.check = (function ( ) {
    return function (  ) {
      var h = location.hash;
          
      if( h != memory ) {
        memory = h;
        if( 'function' === typeof cbFunc )
          cbFunc.call( cbObj, this.getHash( ) );
      }
    };
  })();
  
  
  //初期化
  this.init = (function ( ) {
    return function ( time, func, obj ) {
      this.stop();
      memory = location.hash;
      interval = ( 'number' === typeof time ) ? time: defInterval;
      cbFunc = func || null;
      cbObj = obj || null;
    };
  })();
  
  
  //hashを、オブジェクトにして返す
  this.getHash = (function ( ) {
    var trim = /^\s+|\s+$/g;
    
    return function ( str ) {
      var values = [ ], result = [ ], cnt = 0;
      var obj, tmp;

      if( 'undefined' === typeof str ) str = memory;
      if( /^#/.test( str ) ) str = str.substring(1);

      values = str.split( ';' );

      while( obj = values[ cnt++ ] ) {
        tmp = obj.split( '=', 2 );
        if( 1 < tmp.length ) {
          tmp[0] = tmp[0].replace( trim, '' );
          result[ decodeURIComponent( tmp[0] ) ] = decodeURIComponent( tmp[1] );
        }
      }
    
      return result;
    };
  })();
  
  this.init( interval, cbFunc, cbObj );
  return this.start();

};

function disp( obj ) {
  var txt = '', key = 0, o;
  for( key in obj ) txt += key + '=' + obj[key]+ '\n';
}


HashManager( 1000, disp );
</script>
</body>
</html>