我的问题是有些autoruns会多次被解雇,我想有办法快速查看来源。
我想知道这样的事情是否可能:
let reactive_var_1 = new ReactiveVar();
let reactive_var_2 = new ReactiveVar();
let reactive_var_3 = new ReactiveVar();
let reactive_var_4 = new ReactiveVar();
Template.test.onCreated(function () {
console.log('Template.test.onCreated...');
this.autorun(function () {
console.log('Template.test.onCreated.autorun...');
console.log('autorun source is : ');
console.log(source);
let do_something_1 = reactive_var_1.get() + 1;
let do_something_2 = reactive_var_3.get() + 2;
let do_something_3 = reactive_var_3.get() + 3;
let do_something_4 = reactive_var_4.get() + 4;
});
});
Template.test.events({
'click .something': function () {
console.log('Someone clicked !!');
reactive_var_3.set(12);
}
});
输出控制台应如下所示:
Template.test.onCreated...
Template.test.onCreated.autorun...
autorun source is :
undefined
Someone clicked !!
Template.test.onCreated.autorun...
autorun source is :
'reactive_var_3'
这是我正在寻找的来源功能,可以输出我的' reactive_var_3'
感谢您的帮助:)
答案 0 :(得分:0)
您可以引入另一个缓存变量来跟踪其他变量的状态:
const _cache = {};
const vars = {
reactive_var_1 : new ReactiveVar();
reactive_var_2 : new ReactiveVar();
reactive_var_3 : new ReactiveVar();
reactive_var_4 : new ReactiveVar();
};
在每个autorun
中,您可以检查哪些ractive变量不再与缓存不匹配。以下功能提供了这样的功能:
function diff() {
const diffs = [];
Object.keys(vars).forEach( key => {
const reactiveVar = vars[key];
const value = reactiveVar.get();
// if value is different from state
// it has caused an autorun
if (_cache[key] !== value) {
diffs.push(key);
}
// update cache
_cache[key] = value;
});
return diffs;
}
在autorun
中,您只需调用diff
方法并获取导致跟踪器再次运行的变量的键(名称):
Template.test.onCreated(function () {
console.log('Template.test.onCreated...');
this.autorun(function () {
console.log('Template.test.onCreated.autorun...');
console.log('autorun source is : ');
console.log(diff());
let do_something_1 = reactive_var_1.get() + 1;
let do_something_2 = reactive_var_3.get() + 2;
let do_something_3 = reactive_var_3.get() + 3;
let do_something_4 = reactive_var_4.get() + 4;
});
});
请注意,缓存会立即在diff
函数中更新。如果这限制了您的使用案例,您可以将其提取到单独的函数中,如updateCache
或其他。
另请注意,_cache
存在于模板外部,这在使用同一模板的多个实例时可能会出现问题。然后,您可以切换到另一种方法,并将_cache
和vars
作为局部变量保留在模板实例中:
Template.test.onCreated(function () {
console.log('Template.test.onCreated...');
const _cache = //...
const vars = //...
function diff(){ /* ... */ }
this.autorun(function () {
console.log('Template.test.onCreated.autorun...');
console.log('autorun source is : ');
console.log(diff());
let do_something_1 = reactive_var_1.get() + 1;
let do_something_2 = reactive_var_3.get() + 2;
let do_something_3 = reactive_var_3.get() + 3;
let do_something_4 = reactive_var_4.get() + 4;
});
});