How to reactively call a js function/event with meteor.js


#1

I’m new to meteor.js. Still getting used to it. I get how templates update reactively according to the cursor updates on the server, like this:

{{#if waitingforsomething.length}} Something Happened! {{/if}}

This is good to display elements on the page, updating lists and content. But what if I want to call some javascript or fire an event when something gets updated reactively? What would be the right way to do it with meteor.js?

I’ve posted this on stackoverflow but answers seemed a bit hackish and non-standard, since this should be a very common thing to do on an app workflow, I decided to ask the community here for a better answer.


#2

Tracker is your friend here if you’re looking to control client-side reactivity. So if you wanted to watch a reactive value you could use a file-bound autorun

Tracker.autorun(() => {
    if (reactiveVariable.get() == "desiredValue") {
        doSomething();
    }
})

or more preferably bind it to a template

Template.example.onCreated(function() {
    this.autorun(() => {
        if (FlowRouter.getQueryParam("testParam") == "desiredValue") {
            doSomething();
        }
    })
})

This is a very detailed but incredible resource for all things Tracker in Meteor, recommended read for sure.