Meteor 什么';在某些路径更改上添加挂钩的最干净方法是什么?

Meteor 什么';在某些路径更改上添加挂钩的最干净方法是什么?,meteor,iron-router,Meteor,Iron Router,我想在“路径名称空间”更改时添加一个钩子函数。例如,当路由器从myapp/字段/9837278993转到myapp/列表/183727856时。当然,我可以在mainonBeforeActionhook中使用一些regex条件逻辑。更抽象的逻辑是“当名称空间从字段变为除字段以外的任何字段时,运行钩子。你有什么建议?谢谢你的帮助!我认为你想将逻辑从路由器层抽象出来是正确的(使交换路由器更容易!)。问题是在数据上下文更改之前获取它 要实现这一点,我建议将您的路由器。将行转换为函数。很可能这是在事件内

我想在“路径名称空间”更改时添加一个钩子函数。例如,当路由器从myapp/字段/9837278993转到myapp/列表/183727856时。当然,我可以在main
onBeforeAction
hook中使用一些regex条件逻辑。更抽象的逻辑是“当名称空间从字段变为除字段以外的任何字段时,运行钩子。你有什么建议?谢谢你的帮助!

我认为你想将逻辑从路由器层抽象出来是正确的(使交换路由器更容易!)。问题是在数据上下文更改之前获取它

要实现这一点,我建议将您的
路由器。将
行转换为函数。很可能这是在事件内部,因此IR reactive
current()
不会在这里伤害您

function changePath(path) {
  if (path !== 'fields' && Router.current().route.name === 'fields') {
    //do stuff
  }
  Router.go(path);
}

我最终得到了我自己的完全通用的解决方案,使用了reactivevar
Router.current().location.get()
Tracker.autorun
函数混合使用。因此它100%独立于路由器配置,我认为这是一件好事。用coffeescript编写

简单易用:

Meteor.startup ->  
  RouterTransitions.register('/lists/' ,null,-> console.log("Switching from lists to any"))
预期行为:

  • 当路由从
    /lists/*
    更改为
    /(*)
    其中
    (*)!='lists/'
    时,将运行
    挂钩
    功能
  • 只要目标不是源路径的子路径(例如:
    from/lists/to/lists/1864f
    将不会触发挂钩),就可以从同一个源注册任意数量的转换。但是,源路径可以是目标路径的子路径
资料来源如下:

class RouterTransitions

  #could be any sequence of characters with at least one forbidden in URL standards (RFC 3986, section 2 characters)
  WILDCARD:'>>'

  constructor:->
    Tracker.autorun =>
      newPath=Router.current()?.location.get().path
      if @_oldPath!=newPath
        @_matchingDestinations.forEach (destinations) =>
          origin=destinations.origin
          Object.keys(destinations.targets).forEach (key) =>
            if !newPath.match("#{origin}.*")&&(key==@WILDCARD or newPath.match("#{key}.*"))
              #call the hook
              destinations.targets[key]()
      @_matchingOrigins =Object.keys(@dictionnary).filter (origin) => newPath.match("#{origin}.*")
      @_matchingDestinations = @_matchingOrigins.map (key)=> {
      targets:@dictionnary[key]
      origin:key
      }
      @_oldPath=newPath


  ###
  @param {String} origin : the namespace of the incoming path, null for any match. Origin can be a subset of destination.
  @param {String} destination : the namespace of the forthcoming path, null for any match. Important! destination cannot be a subset of origin
  @param {String} hook : the callback to be run on matching conditions
  ###
  register:(origin,destination,hook) =>
    origin=origin||@WILDCARD
    destination=destination||@WILDCARD
    if @dictionnary[origin]
      @dictionnary[origin][destination]=hook
    else
      hooks=@dictionnary[origin]={}
      hooks[destination]=hook

  #A simple dict with keys='origin' and values plain objects with destinations mapped to hooks
  dictionnary:{}

  _oldPath:'/'

  _matchingDestinations:[]

  _matchingOrigins:[]

window.RouterTransitions=new RouterTransitions()