Search code examples
meteoriron-router

Meteor - How do I automatically redirect user to page when data changes


I am writing a Meteor app that takes in external data from a machine (think IoT) and displays lots of charts, graphs, etc. So far so good. There are various pages in the application (one per graph type so far). Now as the data is being fed in "real-time", there is a situation (normal) where the data "set" gets totally reset. I.e. all the data is no longer valid. When this happens, I want to redirect the user back to the "Home" page regardless of where they are (well, except the home page).

I am hoping to make this a "global" item, but also don't want too much overhead. I noticed that iron:router (that I am using) has an onData()method but that seems a bit -- high overhead -- since it's just one piece of data that indicates a reset.

Since each page is rather "independent" and an user can stay on a page for a long time (the graphs auto-update as the underlying data changes) , I'm not even sure iron:router is the best approach at all.

This is Meteor 1.0.X BTW.

Just looking for a clean "proper" Meteor way to handle this. I could put a check in the redisplay logic of each page, but would think a more abstracted (read: global) approach would be more long-term friendly (so if we add more pages of graphs it automatically still works) ..

Thanks!


Solution

  • This is a job for cursor.observeChanges http://docs.meteor.com/#/full/observe_changes Set up a collection that servers as a "reset notification" that broadcasts to all users when a new notification is inserted.

    On Client:

    criteria = {someCriteria: true};
    query = ResetNotificationCollection.find(criteria)
    var handle = query.observeChanges({
      added: function (id, user) {
        Router.go('home');
      }
    });
    

    Whenever a reset happens:

    notification = { time: new Date(), whateverYouWantHere: 'useful info' }
    ResetNotificationCollection.insert notification
    

    On insert, all clients observing changes on the collection will respond to an efficient little DDP message.