在Backbone.js中有条件地执行路由

Conditionally Execute Routes in Backbone.js

本文关键字:执行 路由 有条件 Backbone js      更新时间:2023-09-26

为了在backbone.js中实现ACL,我正在寻找一种根据某些函数的结果有条件地触发路由的方法。我应该使用execute还是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
    }
});

使用router.navigate()方法可以使用不同的路由。您需要将{trigger: true}作为一个选项传递给它,以便它也调用指定的路由器方法。

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
    }
});