简体   繁体   中英

Meteor: onhashchange does not fire

I have a weird situation. It seems Meteor with Iron::Router is overriding somewhere the onhashchange event however I was unsuccessfully to track it down.

Basically if I listen for that event, it never fires for some reason. I looked and searched everywhere and can not even find any reference to onhashchange in the Meteor code base.

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

This never fires - although the event is properly registered. In plain vanilla it works fine .. so I assume it's somewhere being overwritten.. any insights will be appreciated.

http://jsfiddle.net/L2dj3o7n/

Oh one more thing, this is how my URL's look like right now for testing:

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

etc

From the Router Parameters section of the Iron Router guide :

If there is a query string or hash fragment in the url, you can access those using the query and hash properties of the this.params object.

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

Note: If you want to rerun a function when the hash changes you can do this:

 // 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 is reactive, so if the hash updates, the getParams() call should invalidate and trigger a new computation for whatever you're using it for. For instance, if you wanted to dynamically render a template depending on the hash value, you should be able to do something like this... 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
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM