How do I listen for and react to a blank route using {can.route}?

141 views Asked by At

I want to set up routing with CanJS so that depending on what url I hit, some corresponding control is set up. My problem is trying to find a way of expressing a default route to listen for in the control: "If none match, then do this". Any tips on doing this?

This is my code so far. Seems to work for urls like /#!/plant/1/day/3 and /#!/plant/1, but not for /#! or /

can.route('plant/:plant_id/day/:day', {});
can.route('plant/:plant_id', {});
can.route('', {});

var Router = can.Control({}, {
  init : function () {},

  "{can.route}" : function (route, event, newVal, oldVal) {
    console.log('Init default control');
  },

  "{can.route} plant_id" : function (route, event, newVal, oldVal) {
    console.log('Init plant control');
  },

  "{can.route} day" : function (route, event, newVal, oldVal) {
    console.log('Init day control');
  }
});

P.S. I actually managed to do it using the Can.Control.route plugin by doing this:

"route" : function (route, event, newVal, oldVal) {
    console.log('route Default route', arguments);
}

But the route plugin seems to both set up routes and react to them, and I wanted to know how to do this without the specific plugin.

3

There are 3 answers

0
oligofren On

Ended up doing something like the follow, but it feels less than ideal ...

    "{can.route} change" : function (ev, attr, how, newVal, oldVal) {
        if(newVal=== 'add' && (!ev.attr('plant_id') && !ev.attr('day')))
        console.log('{can.route} Default route', arguments);
    },
2
Daff On

Your solution works but you could also use the can.Control.route plugins which lets you define and listen to routes directly in a controller action:

var Router = can.Control({
    init : function(el, options) {
    },

    "/:plantId route" : function(data) {
        // the route says /id
        // data.id is the id or default value
    },

    route : function(data){
        // the route is empty
    }
});
new Router(window);
0
Marshall Thompson On

I noticed the same problem with the default '/' route. I dove into pushstate.js and found that it wasn't working properly with the default route. You can see more details here: https://forum.javascriptmvc.com/#Topic/32525000001460049

I haven't tested anything without pushstate.js (using #!), so this only applies to using pushstate.