简体   繁体   中英

Trigger method without change route location backbone.js

I have an issue with backbone.js history .

When an user click on a link, I stop the propagation and I would like to call the method matching with the href without changing the location.

$(document).on("click", "a[href^='/']", function(event){
  event.preventDefault();
  event.stopPropagation();
  Router.goToIntraRoute($(event.target).attr("href"));
});

In the backbone router :

var Router = Backbone.Router.extend({
  routes: {
    "user/:id": "openProfile"
  },

  // Changes the location
  modifyRoute: function(route){
    this.navigate(route, {trigger: true, replace: false});
  },

  // Doesn't change the location
  goToIntraRoute: function(route){
    // URL modified
    this.navigate(route, {trigger: false, replace: false});
  }
});

I would like the method goToIntraRoute doesn't modify my url but trigger the method... Can anyone help me?

Assuming that you don't want the new "page" to appear in the history, you could just call the route handler directly. To get you started, here's a simplified example:

goToIntraRoute: function(route){
    if (this.routes[route]) {
        this.routes[route]();
    }
}

To actually use that fragment, you'll need to manage the context ( this ) appropriately. Also, if your routes include wildcards or regular expressions, then you'll have to explicitly parse those from the parameters since you won't be relying on the router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM