gpt4 book ai didi

javascript - 如何响应式调用响应变量引用的 Meteor 方法?

转载 作者:行者123 更新时间:2023-11-30 12:04:10 25 4
gpt4 key购买 nike

我正在尝试调用 Meteor 方法,而不是使用硬编码字符串,而是使用包含其名称的 Session 变量。它工作一次,但当 Session 值通过 Session.set 更改时不会重新运行该方法。

服务器代码:

Meteor.methods({
hello: function () {
console.log("hello");
},
hi: function () {
console.log("hi");
}
});

客户端代码:

Session.set('say', 'hi');
Meteor.call(Session.get('say')); // console prints hi
Session.set('say', 'hello'); // console is not printing, expected hello

如何在 Session 值更改后响应式地调用"new"方法?

最佳答案

你需要一个 react 性上下文来实现这种自制的 react 性。
您可以简单地使用 Tracker.autorun 来实现这一点:

Session.set('say', 'hi');

Tracker.autorun(function callSayMethod() {
Meteor.call(
Session.get('say')
);
});

Meteor.setTimeout(
() => Session.set('say', 'hello'),
2000
);

空格键 template helpers使用这种上下文在模板中实现 react 性。

请注意,您不需要 Session这里。一个简单的ReactiveVar就足够了:

const say = new ReactiveVar('hi');

Tracker.autorun(function callSayMethod() {
Meteor.call(
say.get()
);
});

Meteor.setTimeout(
() => say.set('hello'),
2000
);

关于javascript - 如何响应式调用响应变量引用的 Meteor 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35741755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com