如何从函数中获取UI变量

时间:2012-07-23 18:50:34

标签: javascript function user-interface

如果这是基本的话,我很抱歉。我是自学成才,并且可能会使用Javascript编程的简单功能。任何人都可以告诉我我应该寻找什么来找到合适的答案,或者帮助我一般吗?

我在UI窗口中有一个功能,可以使用面板快速填充它。但我似乎无法将输入到每个面板中的值从UI中移出并进入主“DoSomething”功能。
变量(dlg.tryThis)不会更新?为什么?我需要做什么?

// making a simple UI
function UI_Builder(doSomething)
{
    var dlg = new Window( "dialog", "options" );
    dlg.mainGroup = dlg.add( "group", undefined,"main" );

//Created a simple function so I can re-create panels and values very easy
    function makePanel (panelName, val)  {
        var newPanel = eval("dlg.mainGroup." + panelName);
        newPanel = dlg.mainGroup.add( 'panel', undefined, panelName );
        newPanel.Start = newPanel.add("edittext", [0,0,30,20], val);
        dlg.Start = newPanel.Start.text
        newPanel.Start.onChanging = function()                
                { 
                 dlg.Start = newPanel.Start.text
                  alert("Changed " + panelName + " to:  " + dlg.Start) // THIS alerts correctly.  It know what value I changed and where I changed it. 
                 return dlg.Start;
                 } 
            return dlg.Start;
        } 

    // calling the function to create panels.
    dlg.tryThis = makePanel("tryThis", 4); 
    dlg.anotherOne = makePanel("anotherOne",  3); 
    dlg.again = makePanel("again", 2); 

    dlg.mainGroup.btnCancel = dlg.mainGroup.add( "button",[0,0,130,70], "doSomething" );
    dlg.mainGroup.btnCancel.onClick = function()
    {  
        doSomething();  
     }
 return dlg
}

// all the UI builder is doing is showing the UI
var dlg = UI_Builder(doSomething);
dlg.show();

function doSomething()
{
dlg.close();

alert(dlg.tryThis)  // this is not the NEW value?   How do I get it to be the NEW value updated by the ".onChanging" function? 
}

2 个答案:

答案 0 :(得分:0)

尝试将dlg传递给事件处理程序,而不是全局声明它:

dlg.mainGroup.btnCancel.onClick = function() {
    doSomething(dlg);  
}

function doSomething(dlg) {
    dlg.close();
    alert(dlg.tryThis);
}

如果采用这种方法,则不应在全球范围内声明var dlb,以避免混淆。 (阴影变量通常是一种不好的做法)

答案 1 :(得分:0)

你在没有任何背景的情况下调用doSomething。

使用func.apply:

dlg.mainGroup.btnCancel.onClick = function()
{  
    doSomething.apply(this, []);
}

将对象处理为'this':

function doSomething()
{
    this.close();
    alert(this.tryThis)  // this is not the NEW value?   How do I get it to be the NEW value updated by the ".onChanging" function? 
}