I’m using backbone.js for the front-end of an application. One of the navigation rules is very similar to an authentication flow: the application should only render the views requested by the user if there is a certain piece of information available. Otherwise, another view should be rendered. Whether or not the information is available can be decided by querying the server. What I have tried so far:
//Router table definition, etc...
var initialize = function(){
var appRouter = new AppRouter;
appRouter.on('route:somePage', withInfo(function(){
//render view for 'somePage'
}));
...
The withInfo function is as follows:
function withInfo(f) {
$.ajax({
type: 'GET',
dataType: 'json',
url: '/path/to/info',
success: function (data, status, request) {
var info = $.parseJSON(request.responseText);
if (info){
f.call();
} else {
var defaultView = new DefaultView();
defaultView.render();
}
}
});
}
Basically, what I’m trying to do is define a higher order function with a default behavior. It should call the other function (named f in the code above) if the default behavior doesn’t apply. But this doesn’t work as expected. The function that is actually passed as parameter isn’t always the one declared in the first snippet of code.
Is there another way to do this?
This might not be the best, “dry” way, but it works and doesn’t require any Backbone plugin except the already included Underscore library. This uses the
_.wrapfunction, which wraps the first function inside the second function.and for the
withInfofunction, the only line that changes is the conditional: