如何从函数中获取UI变量

How to get a UI variable out of a function

本文关键字:获取 UI 变量 函数      更新时间:2024-01-26

如果这是基本的,我很抱歉。我自学成才,努力学习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? 
}

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

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

如果采用这种方法,则不应全局声明var dlb,以避免混淆。(隐藏变量通常是一种糟糕的做法)

您在没有任何上下文的情况下调用doSomething。

使用函数应用程序:

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? 
}