唯一的变量名称

时间:2017-12-13 16:20:05

标签: javascript angular ionic3

我在我的ionic3 App中使用ng2-simple-timer

以下是来自repo的代码:

counter: number = 0;
timerId: string;

ngOnInit() {
    this.timerId = this.st.subscribe('5sec', () => this.callback());
}

callback() {
    this.counter++;
}

simpletimer将创建计时器名称并勾选每个“秒”的数字。

回调将返回计数器值(0,1,2,3,4,5,6等等)

我的问题是什么?

我想要定义唯一uniquecounterName: number = 0;,因为我有多个计时器。

我的结果是什么:

  • 返回uniquecounterName(0,1,2,3,4,5,6等等)
  • 返回otheruniquecounterName(0,1,2,3,4,5,6等等)

换句话说,callback()函数必须返回预先定义的唯一变量名,如this.counter

callback(var) {
    var++;
}

这个不起作用,因为我想在我的视图中使用var。 ....

1 个答案:

答案 0 :(得分:0)

似乎不可能,如果你直接从文档中查看“GitHub: ng2-simple-timer-example”,你会发现作者如何处理多个计时器;我不会引用所有代码,您可以自己查看,但只需在此处粘贴回调的方式:

timer0callback(): void {
    this.counter0++;
}

timer1callback(): void {
    this.counter1++;
}

timer2callback(): void {
    this.counter2++;
}

如您所见,整个过程(new,subscribe,del,unsubscribe)都是针对每个计时器完成的。因此,该库不直接支持您的用例。

您可以做的是内联回调函数,以便您可以访问创建它时的相同变量:

function sub(name) {
    this.timerId = this.st.subscribe(name, () => {
        // still have access to the name
    });
}

当然,这必须大大适应您的目的,这是我可以从您的问题中收集到的。

相关问题