javascript - Nativescript getViewById 未更新倒计时

标签 javascript setinterval countdown nativescript

所以,我正在使用我在这个问题中询问的计时器作为倒计时:How to stop timer.setinterval with a tap event or leaving page in nativescript

计数器一直在工作,而我一直在使用 console.log 来检查它是否工作,是的,它确实工作,但我想让它出现在 xml 中,供该应用程序的用户查看。但 xml 中的计数不会更新。

这是 View 的代码:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded" navigatedTo="navigatedTo" navigatingFrom="onNavigatingFrom" actionBarHidden="true">

    <DockLayout orientation="horizontal" horizontalAlignment="center" backgroundColor="black" color="white">
        <Label text="Time remaining: " dock="left" margin="5" />
        <Label id="timeCount" text="" loaded="pageLoaded"></Label>
    </DockLayout>    
</Page>

以及后面的js文件:

var time;
var timeKeep = vm.time;
var count = 0;

function timeCountDown () {
    time = vm.time--;                    //this is the value that i need
    console.log("i is " + time);
}  

countId = timer.setInterval(() => {
    timeCountDown();
    count += 1;
    if (count === timeKeep) {
        timer.clearInterval(countId);
        dialogs.alert({
            title: "Time Up!",
            message: "You did not finish the test in time.",
            okButtonText: "OK"
        });
        aemnavigation.goResults(vm.correct);
    }
}, 1000);  



//the two lines below is how i get it to show on the xml

TimeCountScore = page.getViewById("timeCount");
TimeCountScore.text = time;

时间值到达 View 但未更新,该值已倒计时。我 console.log(time) 以确保它仍然有效。

最佳答案

您应该继承 Observable 类的数据绑定(bind),当属性更改时,它也会更新 XML。对于您的情况,如果您仍然想保持练习,您可以将 label.text 放在间隔内以更新它:

TimeCountScore = page.getViewById("timeCount");

countId = timer.setInterval(() => {
    TimeCountScore.text = time;
}, 1000);  

关于javascript - Nativescript getViewById 未更新倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40372727/

相关文章:

javascript - 在 Javascript/JQuery 中对数组进行排序

javascript - 在 lodash 中改变数组的联合

javascript - 使用 React 定期运行 fetch

java - 如何停止 "Countdown timer "并在Android studio的对话框中显示结果?

javascript - 将 async/await 与 forEach 循环结合使用

javascript - 在没有任何父信息的情况下将展平数组转换为父子数组

javascript - 覆盖 setInterval

javascript - 如何在单击时停止 setInterval 函数,并在几秒钟后重新启动

javascript - JS 中的倒计时

jquery - 如何为 classyCountdown.js 插件设置特定的 GMT 结束时间?