yojimbo87
yojimbo87

Reputation: 68345

Trigger same location route

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.

Upvotes: 16

Views: 9579

Answers (8)

Ravindra Palli
Ravindra Palli

Reputation: 1

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.

Upvotes: 0

andrewmart.in
andrewmart.in

Reputation: 1703

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

Upvotes: 0

Iron
Iron

Reputation: 2

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.

Upvotes: 0

mgauthier
mgauthier

Reputation: 331

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}

Upvotes: 2

eddywashere
eddywashere

Reputation: 2618

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.

Upvotes: 52

Joey V.
Joey V.

Reputation: 1926

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

Upvotes: 1

joshvermaire
joshvermaire

Reputation: 1475

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

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

Upvotes: 3

ProTom
ProTom

Reputation: 1194

Router.navigate('about', true);

That way you can trigger a route manually.

Upvotes: 6

Related Questions