Backbone.js - 触发路由之前/之后的调用方法

Lev*_*lum 9 router routes backbone.js

我希望在我的Backbone.js路由器中分别触发路由之前和之后调用setup/teardown方法.有人创造了一种优雅的方式吗?

Ale*_*hin 9

_.wrap不是一个解决方案,如果您有20个路由,则必须将它们全部包装起来.

但你可以用元编程来做到这一点

class Backbone.FlexRouter extends Backbone.Router
  route: (route, name, handler) ->
    super route, name, ->
      @trigger "route:before"
      handler()
      @trigger "route:after"
Run Code Online (Sandbox Code Playgroud)

UPD:我相信JS应该是这样的(但我没有测试过)

var rp = Backbone.Router.prototype
rp.routeWithoutEvents = rp.route
rp.route = function(route, name, handler){
  var that = this
  this.routeWithoutEvents(route, name, function(){
    that.trigger("route:before")
    handler()
    that.trigger("route:after")
  })
}
Run Code Online (Sandbox Code Playgroud)

  • 这看起来像一个可靠的解决方案,但我有一个问题,我无法阅读coffeesript.有什么方法可以将其翻译成javascript.我已经尝试过在线编译器,但这使得代码对我来说更难以理解. (5认同)
  • @AmebaSpugnosa链接解决方案? (2认同)

pdo*_*926 8

你考虑过_.wrap吗?


小智 6

这是一个简单的,覆盖Backbone.Router本身

(function () {
    _.extend(Backbone.Router.prototype, Backbone.Events, {        
        route: function (route, name, callback) {           
            if (!_.isRegExp(route)) route = this._routeToRegExp(route);
            if (!callback) callback = this[name];
            Backbone.history.route(route, _.bind(function (fragment) {               
                var args = this._extractParameters(route, fragment);                
                if (this.before && _.isFunction(this.before)) {
                    this.before(fragment);
                }                
                callback && callback.apply(this, args);
                this.trigger.apply(this, ['route:' + name].concat(args));
                if (this.after && _.isFunction(this.after)) {
                    this.after(fragment);
                }
                Backbone.history.trigger('route', this, name, args);
            }, this));
            return this;
        }
    });
}).call(this);
Run Code Online (Sandbox Code Playgroud)

专注于线条

if (this.before && _.isFunction(this.before)) {
    this.before(fragment);
}
Run Code Online (Sandbox Code Playgroud)

if (this.after && _.isFunction(this.after)) {
    this.after(fragment);
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要修改线条

这是使用新的Backbone.Router类的客户端代码

var appRouter = Backbone.Router.extend({

routes: {},
before: function(){
   //your code here
   return true;
}

});
Run Code Online (Sandbox Code Playgroud)