流星:onhashchange不会开火

Meteor: onhashchange does not fire

本文关键字:开火 onhashchange 流星      更新时间:2023-09-26

我遇到了一个奇怪的情况。看起来Meteor with Iron::Router在某个地方覆盖了onhashchange事件,但我没有成功追踪到它。

基本上,如果我听那个事件,它永远不会因为某种原因而起火。我到处找,甚至在Meteor代码库中找不到任何关于onhashchange的引用。

if(Meteor.isClient) {
  window.addEventListener('hashchange', function() {
    alert('changed');
  });
}

尽管事件已正确注册,但它从未启动。在纯香草中效果很好。。所以我认为它在某个地方被覆盖了。。任何见解都将不胜感激。

http://jsfiddle.net/L2dj3o7n/

哦,还有一件事,这就是我的URL现在测试的样子:

http://localhost:3000/#/workflow
http://localhost:3000/#/settings/account
http://localhost:3000/#/group/add

etc

来自Iron Router指南的Router Parameters部分:

如果url中有查询字符串或哈希片段,则可以访问使用this.params对象的查询和散列属性的那些。

// given the url: "/post/5?q=s#hashFrag" 
Router.route('/post/:_id',
function () {   
    var id = this.params._id;   
    var query = this.params.query; // query.q -> "s"   
    var hash = this.params.hash; // "hashFrag" 
});

注意:如果您想在哈希发生更改时重新运行函数,您可以执行以下操作这个:

// get a handle for the controller. 
// in a template helper this would be 
// var controller = Iron.controller(); 
var controller = this;
// reactive getParams method which will invalidate the comp if any part of the params change 
// including the hash. 
var params = controller.getParams();

getParams是被动的,所以如果哈希更新,getParams()调用应该会使您使用它的任何内容无效并触发新的计算。例如,如果您想根据哈希值动态呈现模板,您应该能够执行以下操作。。。HTML:

<template name='myTemplate'>
  {{> Template.dynamic template=getTemplateFromHash}}
</template>

JS:

Template.myTemplate.helpers({
  getTemplateFromHash: function() { 
    var hash = Iron.controller().getParams().hash;
    ... // do whatever you need to do with the hash to figure out the template to render
  }
});