当反应变量改变值时,为什么这个函数 运行 不起作用?

Why doesn't this function run when the reactive variable changes value?

我是 meteor 的新手,我正在尝试了解整个反应性问题。

没有特定的原因我希望此函数重新 运行,事实上,它不重新 运行 实际上是我的用例所需的行为。我只想知道为什么会这样,这样我才能更好地理解这些概念。

如果我在模板实例上添加一个函数作为 属性,如下所示:

Template.services.onCreated( function() {
    this.templates = [
        "web_design",
        "painting",
        "gardening"
    ];
    this.current_index = new ReactiveVar(0);

    this.determineSlideDirection = function() {
        console.log(this.current_index.get());
    };
});

然后我更新反应变量以响应某些事件。

Template.services.events({
    'click .nav-slider .slider-item': function(event, template) {
        var new_selection = event.currentTarget;
        template.current_index.set($(new_selection).index());
    }
});

调用 set() 调用时,函数不会重新 运行。

但是,如果我有一个使用变量的 helper,它将重新 运行。

Template.services.helpers({
    currentTemplate: function() {
        var self = Template.instance();
        return self.templates[self.current_index.get()];
    }
});

这是为什么?

响应式数据源只会导致某些功能自动重新运行。这些函数是:

  • Tracker.autorun
  • Template.myTemplate.helpers({})
  • Blaze.renderBlaze.renderWithData

在您上面的代码中,您需要使用 Tracker.autorun

Template.services.onCreated( function() {
    this.templates = [
        "web_design",
        "painting",
        "gardening"
    ];

    this.current_index = new ReactiveVar(0);

    Tracker.autorun(function(){
        // actually, this might not work because the context of
        // 'this' might be changed when inside of Tracker.
        this.determineSlideDirection = function() {
            console.log(this.current_index.get());
        };
    });
});