Domanda

I've hooked the window.onbeforeunload event and the Marionette.AppRouter.navigate method to detect navigation off a page and run some code before navigating.

These hooks trigger on closing the page or navigating around except in the case of back or forward button navigation (Chrome).

I can handle the route event and detect when the back/forward button is invoked:

  Backbone.history.on('route', function(route, params) {
    console.log('routing!');
  });

But I want to be able to do it before navigation; extending execute should let me do that but it doesn't get invoked:

  _.extend(Backbone.Router.prototype, {
    execute: function(callback, args) {
      if (callback) callback.apply(this, args);
    }
  });
È stato utile?

Soluzione

Turns out what worked was to override the Backbone.Router and then add logic to conditionally execute the line with callback.apply:

  _.extend(Backbone.Router.prototype, {
    route: function(route, name, callback) {
      var that = this;
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (!callback) callback = this[name];
      Backbone.history.route(route, _.bind(function(fragment) {
        var args = that._extractParameters(route, fragment);
        if (myCustomLogic) {
          callback && callback.apply(that, args);
          that.trigger.apply(that, ['route:' + name].concat(args));
          that.trigger('route', name, args);
          Backbone.history.trigger('route', that, name, args);
        }
      }, that));
      return that;
    },
  });

Appears that the browser forward/back buttons are getting handled by Backbone.Router where other navigation is handled via Marionette.AppRouter.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top