Trigger same location route

2019-02-04 10:24发布

问题:

Is there a way to trigger same location route in backbone.js, for example when location is /My/App/#/About and user clicks again on anchor with the same route in order to refresh the page content.

回答1:

Router.navigate('about', true);

That way you can trigger a route manually.



回答2:

Backbone.history.loadUrl(Backbone.history.fragment);

The solution for your specific problem isn't really documented and it seems the suggested best practice is to just call the function that is declared in the route you want to fire :/

Ref: https://github.com/documentcloud/backbone/issues/1214

So far the other answers are correct, but they forgot to mention that if the hash navigated to is the same as the current hash, nothing will fire.



回答3:

Assuming you want to do this for more than just the About page, use:

route = Backbone.history.fragment;
yourRouter.navigate(route, true);


回答4:

Since the Backbone router looks for changes in the URL fragment you want to load, what worked for me is to navigate to '/' first without trigger, and then subsequently to the URL (fragment) you want to hit with the trigger. You could probably build this into the default router behavior pretty easily if you wanted.

e.g.

App.Routers.appRouter.navigate '/', {trigger: false}
App.Routers.appRouter.navigate myPath, {trigger: true}


回答5:

Using Backbone 0.9.2 you pass in an options object and set 'trigger' to 'true'.

router.navigate('some/route', { trigger : true });

Reference: http://documentcloud.github.com/backbone/#Router-navigate



回答6:

Another option : you can add a parameter with a random value, so hash will be different for each call, even if you call the same page.



回答7:

Thanks for the suggestion @eddywashere, truly awesome. I added a little edit to mine that checks if you're on the last (most currentl) url, and if so, loads that history. Pretty simple, thought it might help someone with the same issue.

$("[data-href]").on("click", function(e) {
  var href;
  e.preventDefault();
  href = $(e.currentTarget).data("href");
  if ((_.last(this.history)) === href) {
    return Backbone.history.loadUrl(_.last(this.history));
  } else {
    return this.router.navigate(href, true);
  }
});


回答8:

router.navigate(route, {trigger: false}); // Changes URL but it will not trigger...Ex: In place of route -- 'about/1' or 'about' etc

Backbone.history.loadUrl(Backbone.history.fragment); // Changed route will be triggered here.