2016-11-02 26 views
1

所以,我使用,我詢問了這個問題的定時器作爲倒計時:How to stop timer.setinterval with a tap event or leaving page in nativescriptNativescript getViewById沒有更新的倒計數

計數器的作品,我一直在使用的console.log檢查而所有這一切如果它的工作原理和是的,但它確實,但我想讓它出現在該應用程序的用戶看到的XML。但計數不會在xml中更新。

下面是視圖代碼:

<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; 

的時間值上的看法,但它沒有更新的值爲倒計時。我console.log(時間),以確保它仍然計數。

+0

能夠更新你應該使用'數據Binding'了'Label' text屬性和將標籤的text屬性與'id =「timeCount」'綁定。更多關於這個,你可以在這裏的文檔中找到 - http://docs.nativescript.org/core-concepts/data-binding#binding-in-xml,在那裏你也可以找到如何做到這一點的例子。 –

回答

1

你應該data binding繼承了Observable類,當一個屬性被改變時它也會更新XML。對於你的情況,如果你仍然想保持你的練習,你可以把label.text的時間間隔內得到它更新:

TimeCountScore = page.getViewById("timeCount"); 

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

非常感謝。它現在可以按照您的建議進行操作。 – Joel

+0

@Nikolay Tsonev,也謝謝。我已閱讀過有關數據綁定的文檔。只是無法讓它使用該方法,因此使用getViewById方法。猜猜我得晚點解決。 – Joel