Skip to content

Instantly share code, notes, and snippets.

@mach3
Created September 15, 2011 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mach3/1219138 to your computer and use it in GitHub Desktop.
Save mach3/1219138 to your computer and use it in GitHub Desktop.
location.hashの変更イベントを受け取るためのもの。
/*!
* HashChange.js
* @version 1.0
* @author mach3
* @example
* var foo = new HashChange();
* foo.config({ onInit:myInitFunc, onChange:myChangeFunc, interval:100 });
* foo.start(); // When start to observe.
* foo.stop(); // When stop to observe.
*/
/**
* Creates a new HashChange.
* @constructor
* @class observe changes of locatin.hash.
* @param {Object} options Configuration options.
*/
var HashChange = function( options ){
var my, vars, methods ;
my = this;
vars = {
onChange : null,
onInit : null,
interval : 100,
timer : null,
hash : null
};
methods = {
isFunction : function( target ){
return typeof( target ) === "function" ;
}
};
/**
* Configure options.
* @param {Object} options Configuration options.
*/
my.config = function( options ){
for( i in options ){
if( !vars.hasOwnProperty( i ) ){ continue; }
vars[i] = options[i];
}
};
/**
* Start to observe.
*/
my.start = function(){
my.run();
};
/**
* Check whether location.hash has been changed or not,
* call onInit/onChange function if set,
* and call itself by timeout again.
*/
my.run = function(){
var h = location.hash;
if( vars.hash === null && methods.isFunction( vars.onInit ) ){
vars.onInit( h );
} else if ( vars.hash !== h && methods.isFunction( vars.onChange ) ){
vars.onChange( h );
}
vars.hash = location.hash;
vars.timer = setTimeout( my.run, vars.interval );
};
/**
* Stop to observe.
*/
my.stop = function(){
clearTimeout( vars.timer );
};
my.config( options );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment