简体   繁体   English

使用meteor.js反应性地调用js函数/事件

[英]Reactively call a js function/event with meteor.js

I'm new to meteor.js. 我是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? 现在,我的问题是:当我要响应性地更新某些内容时,如果我想调用一些JavaScript或触发某个事件该怎么办? What would be the right way to do it with meteor.js? 使用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. 这有点过时了,但是Sacha Greif的“ 反应性基础知识”是对流星反应性模型的快速而简洁的介绍。

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. 基本上,您具有所谓的reactive computations ,该代码观察特殊的数据对象( sessionssubscriptionscursors等),并且只要这些reactive sources任何一个发生更改,代码便会执行。

This is exposed via the Tracker API 这是通过Tracker API公开的

Anything inside Tracker.autorun or template instance this.autorun runs with changes in reactive data sources inside these autoruns. Tracker.autorun模板实例中的任何内容, Tracker.autorun都会在Tracker.autorun this.autorun运行中的反应性数据源发生更改的情况this.autorun运行。

Reactive data sources are ReactiveVar instances, db queries, Session variables, etc. 反应性数据源是ReactiveVar实例,数据库查询, Session变量等。

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. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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