Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a route in Backbone js

Tags:

backbone.js

Similar to Django's {{ url }}, is there a method or way to reverse a particular route by passing it a name and variables.

// example Router
var router = Backbone.Router.extend({
    routes: {
        '!/user/:user_id': 'editUserAction',
        '!/': 'homeAction'
    },
    editUserAction(user_id) {
        // edit user view
    },
    homeAction() {
        // home view
    }
});

Some method like

router.reverse('editUserAction', '5');

Would return the hash: !/user/5

router.reverse('homeAction');

Would return the hash: !/

like image 522
dlrust Avatar asked Oct 04 '11 23:10

dlrust


2 Answers

A discussion about reverse routing. https://github.com/documentcloud/backbone/issues/951

a simple hack

var personRoutes = {
  list: "/persons",
  show: "/persons/:id",
  edit: "/persons/:id/edit"
}

var getRoute = function(obj, route, routeDefinitions){
  return routeDefinitions[route].replace(":id", obj.id);
}

var person = new Model({id: 1});
var route = getRoute(person, "edit", personRoutes); // => "/persons/1/edit"
like image 130
fxp Avatar answered Nov 02 '22 00:11

fxp


Unfortunately no, there isn't anything like this built in to backbone. I've wanted something similar and there has been discussion of this on the list once or twice - maybe even a pull request (don't remember for sure at the moment). But it has not yet been done.

The best that I've come up with is to write my own methods that produce the correct route string:

function userEditPath(userId){
  return "/user/" + userId + "/edit";
}
like image 4
Derick Bailey Avatar answered Nov 01 '22 23:11

Derick Bailey