backbone iterate over router
I have parts of the site that can be loaded via WebSocket (and render with
underscore), or if a view doesn't exist for that particular URI, it should
load via ajax.
I would like to bind a event for each link from site, check if the URI is
in my router. If it is, navigate to it and trigger the function from the
router which does the job. If it's not, navigate to it, but don't trigger.
Make the ajax request and just put the html under #main.
Here is part of my route (you see routes are traditionally defined via the
"routes" key, but also via this.route):
Router = Backbone.Router.extend({
routes: {
"about": "about",
"*path": "notFound"
},
initialize: function() {
this.route(/g\/([a-z0-9]{2,})$/, "game");
this.route(/rank\/([0-9]{1,})$/, "rank");
//...
},
//...
});
What I would like (this code works, but I need the variabile "Router"
populated (http://jsfiddle.net/3jdSe/):
var Router = {
'routes': [
{
'uri' : 'about'
},
{
'uri' : /rank\/([0-9]{1,})$/
},
]
};
doesUriExistInRouter = function(uri) {
var routeFound = null;
_(Router.routes).each(function(route){
var routeUri = route.uri;
var regexPattern = null;
if( routeUri.toString()[routeUri.toString().length - 2] == '$' )
{// is defined as regex
regexPattern = new RegExp( '^' + routeUri.toString().substr(0,
routeUri.toString().length - 2) + '$' );
} else {
regexPattern = new RegExp( '^' + routeUri + '$' );
}
if (!_.isNull(uri.match(regexPattern))) {
routeFound = routeUri;
return;
}
});
return routeFound != null ? routeFound : false;
}
_(['about', '/rank/2', 'nope']).each(function(uri){
if(doesUriExistInRouter(uri) !== false) {
console.log('Router for '+uri+' found');
} else {
console.log('Router for '+uri+' NOT found');
}
});
I may have some alternatives (although are hack-y). I hesitated to do some
other things that were so easy to solve via a simple iterator and a regex
match. So I'm asking you now.
Thanks in advance!
No comments:
Post a Comment