baseprime / grapnel

The smallest JavaScript router with named parameters, HTML5 pushState, and middleware support
http://grapnel.js.org
467 stars 40 forks source link

Stop Propagation when more than one URL is match #12

Closed sarriaroman closed 9 years ago

sarriaroman commented 10 years ago

Hi,

First of all, your library is great, simple, flexible and very fast. In the last days I was requiring to stop the propagation of a match because I had to prepare an app when nothing is matched using the wildcard * but with the normal behaviour the wildcard will be matched also on each match. So I made a very simple change to stop the propagation of an event. When a hash is matched will stop the propagation so no other match will be triggered.

Here is the change: http://www.mergely.com/PfNmOxS5/

Best :)

baseprime commented 10 years ago

Thank you so much for your contribution! I think Grapnel definitely needs functionality to stop propagation of other matched routes. I'll put this in the next release, which should also include HTML5 pushState. :]

supermensa commented 9 years ago

This is a great router and nice that you included support for HTML5 pushState, which I am using.

However, I'm having a problem where I need to implement something similar. I need to match both a front page route and wildcard for 404 pages.

The stopPropagation fix, that @sarriaroman provided for an older version of Graphnel, works when triggering routes, but does not fire when entering a page (it only fires on navigate event).

I need to match the front page with "" or / and 404 pages with *. Right now the wildcard route is firing on all pages.

Here's my setup:

var routes = {

    // Front page
    '' : function(req){
      console.log("front page", req)
    },
    // Product pages
    'products/:id?' : function(req){
      console.log("single product page", req)
    },
    // 404 pages
    '*' : function(req){
      console.log("404", req );
    }

}

var router = Grapnel.listen({ pushState : true, root: '/'}, routes);

// this only works when using router.navigate
router.on('match', function(event){

    console.log('matching route');
    event.stopPropagation();
    event.preventDefault();

});

I'd be happy to try and implement this and submit a pull request, but would need some advice.

I'm not sure if the route for the front page should match a slash '/' or nothing ''

baseprime commented 9 years ago

I think that event.stopPropagation() support should be added, it would make handling 404s much easier.

ckken commented 9 years ago

@sarriaroman it cant Stop Propagation when more than one URL is match

supermensa commented 9 years ago

@ckken How about executing the callback on the first match?