Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aborting navigation with Meteor iron-router

I have a (client-side) router in a Meteor app, and links using the {{pathFor}} helper.

I am setting a dirty flag in the Session when the user changes a form field, and I want to trigger a warning and allow the user to stop navigating away from the page if the flag is set, basically like an onunload handler.

I've tried to do this with:

Router.onBeforeAction(function(pause) {
    var self = this;

    if (!this.ready()) {
        return;
    }

    if(Session.get('dirty')) {
        if(!confirm("Are you sure you want to navigate away?")) {
            pause();
        }
    }
});

However, whilst I get the prompt, I'm still being navigated away. That is, the pause() doesn't seem to stop the subsequent router action, whatever it is.

What am I doing wrong?

like image 543
optilude Avatar asked Jun 23 '14 14:06

optilude


1 Answers

From what I can tell this isn't possible with the iron-router API. What you could do however is override the Router.go method like so (somewhere in your client code):

var go = Router.go; // cache the original Router.go method
Router.go = function () {
  if(Session.get('dirty')) {
    if (confirm("Are you sure you want to navigate away?")) {
      go.apply(this, arguments);
    }
  } else {
    go.apply(this, arguments);
  }
};
like image 124
Dave Avatar answered Sep 24 '22 06:09

Dave