Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active August 29, 2015 14:23
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 barneycarroll/651a6cbbdc6075d8f8f8 to your computer and use it in GitHub Desktop.
Save barneycarroll/651a6cbbdc6075d8f8f8 to your computer and use it in GitHub Desktop.
A custom attribute for routing
function route( node, route, attrs ){
if( route instanceof String )
route = [ route, {} ]
var uri = route[ 0 ]
var params = route[ 1 ]
var config = attrs.config
for ( var key in params )
if ( params.hasOwnProperty( key ){
var placeholder = ':' + key
var delimiter = uri.indexOf( '?' ) > -1 )
? '&'
: '?'
if( uri.indexOf( placeholder ) > -1 ){
uri = uri.replace(
placeholder,
params[ key ]
)
}
else {
uri += delimiter + params[ key ]
}
}
uri = uri.replace( /:([^\/:?&#]+)/g, function( match, param ){
return m.route.param( param )
} )
node.href = uri
node.config = config
? function(){
config.apply( this, arguments )
m.route.apply( this, arguments )
}
: m.route
}
@barneycarroll
Copy link
Author

Simple usage:

m( 'a', {
    route : '/location'
} )
// Instead of 
m( 'a', {
    href   : '/location',
    config : m.route
} )

For more complex needs:

m( 'a', {
    route : [ '/:user/:project', {
        user    : 'barney',
        project : 'mattr',
        page    : 2
    } ]
} )
// The resulting URI will be:
'/barney/mattr?page=2'

@barneycarroll
Copy link
Author

  • Todo: fill in unspecified placeholders from the current route

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment