简体   繁体   中英

Reactively call a js function/event with meteor.js

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. Now, my question is: what if I want to call some javascript or fire some event when something gets updated reactively? What would be the right way to do it with meteor.js?

It is a little bit outdated, but Sacha Greif's Reactivity Basics is a very quick and concise introduction to meteor's reactivity model.

Basically, you have what's called reactive computations , code that observes special data objects ( sessions , subscriptions , cursors , etc.) and gets executed whenever any of these reactive sources changes.

This is exposed via the Tracker API

Anything inside Tracker.autorun or template instance this.autorun runs with changes in reactive data sources inside these autoruns.

Reactive data sources are ReactiveVar instances, db queries, Session variables, etc.

Template.myTemplate.onCreated(function() {

  // Let's define some reactive data source
  this.reactive = new ReactiveVar(0);

  // And put it inside this.autorun
  this.autorun(() => console.log(this.reactive.get()));
});

Template.myTemplate.events({
  // Now whenever you click we assign new value
  // to our reactive var and this fires
  // our console.log
  'click'(event, template) {
    let inc = template.reactive.get() + 1;
    template.reactive.set(inc);
  }
});

Computation works pretty well for me:

  Template.myTemplate.onRendered(function() {
        this.computation = Deps.autorun(function () {
            if (something) {
                $(".reactive").html("Something Happened!");
            }
         });
    });

Template.myTemplate.destroyed = function(){
    if (this.computation){
        this.computation.stop()
    }
};

I Hope this helps.

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