如何使用 {can.route} 侦听和响应空白路由

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

本文关键字:响应 空白 路由 何使用 can route      更新时间:2023-09-26

我想用CanJS设置路由,以便根据我点击的url,设置一些相应的控件。我的问题是试图找到一种表达默认路由的方法,以便在控件中侦听:"如果没有匹配,则执行此操作"。有什么提示吗?

这是我到目前为止的代码。似乎适用于 /#!/plant/1/day/3/#!/plant/1 等网址,但不适用于/#!/

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

附言我实际上设法使用 Can.Control.route 插件做到了这一点:

"route" : function (route, event, newVal, oldVal) {
    console.log('route Default route', arguments);
}
但是路由插件

似乎既设置了路由又对它们做出了反应,我想知道如何在没有特定插件的情况下做到这一点。

您的解决方案有效,但您也可以使用罐头。Control.route 插件,可让您直接在控制器操作中定义和侦听路由:

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

最终做了类似以下内容的事情,但感觉不太理想......

    "{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);
    },

我注意到默认的"/"路由也有同样的问题。 我潜入 pushstate.js发现它在默认路由下无法正常工作。 您可以在此处查看更多详细信息:https://forum.javascriptmvc.com/#Topic/32525000001460049

我没有测试过没有 pushstate .js(使用 #!)的任何内容,所以这仅适用于使用 pushstate。