2012-10-05 69 views
2

我想製作一個跟蹤按鈕按下時間的腳本。衆所周知,JavaScript缺乏對靜態變量的支持,但通常可以在目標函數之外定義變量。是否有可能在處理程序中有一個靜態變量?

儘管如此,這並不適用於我簡單的谷歌腳本Web應用程序。代碼是以下代碼,它是模板Web應用程序的簡單擴展。

任何人都知道如何做到這一點?

這是谷歌應用程序的代碼:

// Script-as-app template. 

function doGet() { 
    var app = UiApp.createApplication(); 
    var button = app.createButton('Click Me'); 
    app.add(button); 
    var label = app.createLabel('The button was clicked.') 
       .setId('statusLabel') 
       .setVisible(false); 
    app.add(label); 
    myClickHandler.counter = 0; 

    var handler = app.createServerHandler('myClickHandler'); 
    handler.addCallbackElement(label); 
    button.addClickHandler(handler); 

    return app; 
} 

function myClickHandler(e) { 
    var app = UiApp.getActiveApplication(); 

    var label = app.getElementById('statusLabel'); 
    label.setVisible(true); 
    label.setText('Clicked ' + myClickHandler.counter + ' times.') 
    myClickHandler.counter++; 
    //app.close(); 
    return app; 
} 

回答

2

有幾種可能的方式來實現,這裏使用的是隱藏控件保存值其中之一。

function doGet(){ 
    var app = UiApp.createApplication(); 
    var button = app.createButton('Click Me'); 
    app.add(button); 
    var counterValue = 0; 
    var label = app.createLabel('The button was clicked.') 
       .setId('statusLabel') 
       .setVisible(false); 
    var counter = app.createHidden('counter').setId('counter').setValue(counterValue)    
    app.add(label).add(counter); 

    var handler = app.createServerHandler('myClickHandler'); 
    handler.addCallbackElement(counter); 
    button.addClickHandler(handler); 

    return app; 
} 

function myClickHandler(e) { 
    var app = UiApp.getActiveApplication(); 

    var label = app.getElementById('statusLabel'); 
    label.setVisible(true); 
    var counterValue = Number(e.parameter.counter) 
    var counter = app.getElementById('counter') 
    counterValue++; 
    counter.setValue(counterValue.toString()) 
    label.setText('Clicked ' + counterValue + ' times.') 
    return app; 
} 
+0

我一直在尋找更重要的東西,但我不能否認,這真的使伎倆。謝謝! – luimarma

相關問題