简体   繁体   中英

Conditionally Execute Routes in Backbone.js

Working towards implementing ACL in backbone.js, I was looking for a method to conditionally trigger routes based on the outcome of some function. Should I use execute or route ?

 function isRouteAuthorized(route, name) { // returns true or false depending on some conditions } Backbone.Router.extend({ routes: {"": "users", "resources": "resources",}, route: function (route, name, callback) { if (isRouteAuthorized(route, name)) { //follow to route // How to achieve this ?? } else { //go to error route // How to achieve this ?? } }, users: function () { //display users view }, resources: function () { //display resources view }, error: function () { //display error view } }); 

Use the router.navigate() method to use a different route. You'd need to pass {trigger: true} as an option to it so that it invokes the specified router method as well.

 Backbone.Router.extend({ routes: {"": "users", "resources": "resources",}, execute: function (callback, name, args) { if (condition) { //follow to route callback.apply(this, args); } else { //go to error route this.navigate('error', {trigger: true}); } return false; }, users: function () { //display users view }, resources: function () { //display resources view }, error: function () { //display error view } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM