Return to Snippet

Revision: 6829
at June 17, 2008 15:54 by 6e


Initial Code
document.observe('dom:loaded', function(){
	// instance the class...it is available via 'controller'
	controller = new StateController();
});

var StateController = Class.create({
	
	initialize: function(){
		util.trace('Control this.');
		
		this.lastHash = '';
		this.ready = true;
		
		Event.observe(window, 'load', this.loaded.bind(this));
		document.observe('receiver:stateChange', this.stateChange.bind(this));
		//document.observe('receiver:hashChange', this.hashChange.bind(this));
	},
	
	loaded: function(){
		util.trace('Got loaded');
		//observe for hash changes
		this.observeHash();
	},
	
	stateChange: function($event){
		// when a state change is invoked, change the hash
		util.trace('change hash '+ window.location.hash);
		// add slash for aesthetics...looks like swfaddress
		this.setHash($event.memo.destination);
	},

	observeHash: function(){
		//when hash changes fire receiver:hashChanged
		new PeriodicalExecuter(function(pe){
			if (window.location.hash == this.lastHash) {
				// hash hasn't changed, bail
				return;
			}
			// hash has changed, take note and fire receiver:stateChange
			this.lastHash = window.location.hash;
			util.trace('New hash');
			document.body.fire('receiver:hashChange', {destination: window.location.hash});
			
		}.bind(this), .1);
  	},
	
	fireEvent: function($destination){
		//method for flash to send destination
		document.body.fire('receiver:stateChange', {destination: $destination});
	},
	
	getHash: function(){
		// returns the hash stripped of #/
		return window.location.hash.sub('#/', '')
	},
	
	setHash: function($destination){
		// formats hash to #/destination
		window.location.hash = '/'+$destination;
	},
	
	getRelativeURL: function($url){
		// pulls protocol, host and path from url to return location
		var absolute = window.location.protocol+'//'+window.location.host+window.location.pathname;
		util.trace(absolute+ '  ' + $url);
		return $url.sub(absolute, '');
	},
	
	ready: function(){
		return this.ready;
	},
	
	sitePageTitle: function(destination, delimiter){
		var pathArray = destination.split('/').invoke('capitalize');
		pathArray.unshift(document.title.split(' '+delimiter+' ').last());
		pathArray.reverse();
		return pathArray.join(' '+delimiter+' ');
	}
	
});

Initial URL


Initial Description


Initial Title
State Controller

Initial Tags
ajax, javascript, textmate

Initial Language
Other