Jason
Jason

Reputation: 65

Hashing error with crossroads.js

I'm testing out crossroads.js and hasher.js together and the following code errors on the second setHash call, with "Function.prototype.apply: argument is not an Object". This is both in IE and Chrome.

crossroads.addRoute( 'lorem/{id}', function( id ) { alert( id ); } );

hasher.changed.add( crossroads.parse, crossroads );
hasher.init();

hasher.setHash('lorem/123');  // works with alert(123)
hasher.setHash('lorem/456');  // javascript error

Am I doing something wrong here? The first setHash shows the alert fine.

Upvotes: 0

Views: 873

Answers (1)

Jason
Jason

Reputation: 65

I worked out what the problem is. The crossroads.parse has the wrong signature (request, defaultArgs) for the hasher.changed signal and shouldn't be added directly with this code: hasher.changed.add(crossroads.parse, crossroads). If I pass in a proxy method with signature (newHash, oldHash) it works:

crossroads.addRoute( 'lorem/{id}', function( id ) { alert( id ); } );
var proxy = function( newHash, oldHash ) { crossroads.parse( newHash ); };

hasher.changed.add( proxy );  // Use to be hasher.changed.add( crossroads.parse, crossroads );
hasher.init();

hasher.setHash('lorem/123');
hasher.setHash('lorem/456');

The reason it works the first time is because there's no oldHash and so no defaultArgs. And defaultArgs gets initialised to an empty array at the beginning of the parse method if it's blank.

But this works a little too well because now I'm now getting two alerts for each setHash call.

Upvotes: 3

Related Questions