【问题标题】:Angular Typescript - waiting for a value from a popup dialogAngular Typescript - 等待弹出对话框中的值
【发布时间】:2017-10-26 16:12:59
【问题描述】:

我有一个 html 按钮,当按下该按钮时,会调用一个函数,该函数将“显示”布尔值设置为 true,这会显示一个弹出对话框,用户可以在其中从名称列表中选择一个名称。选择名称会将“selectedName”变量设置为所选名称。

这是我的问题 - 我最初调用以显示弹出对话框的同一个函数需要对所选名称进行更多处理 - 我想在一个函数调用中完成所有这些。像这样的:

// Called by pressing an HTML button
getSelectedName() {
    display = true; // makes dialog popup appear

    // Wait for user to select a name and press a 'Confirm' button 
    // within the dialog popup

    // Once the user has selected a name, do something with it
    var person: Person;
    person.name = selectedName;
}

弹出对话框有确认/取消按钮——有没有办法让上述函数等待用户点击确认按钮,然后在函数中继续?

【问题讨论】:

    标签: html angular typescript wait


    【解决方案1】:

    您可以创建一个在用户单击确认后解决的承诺,然后仅在该承诺解决后执行您需要的任何工作。

    // Called by pressing an HTML button
    getSelectedName() {
        display = true; // makes dialog popup appear
    
        // Create a promise that resolves when button is clicked.
        const buttonPromise = new Promise((resolve) => {
            const button = document.getElementById("my-confirm-button");
            const resolver = () => {
                resolve();
                button.removeEventListener("click", resolver);
            }
    
            button.addEventListener("click", resolver);
        });
        
    
        // Once the user has selected a name, do something with it       
        buttonPromise.then(() => {
            var person: Person;
            person.name = selectedName;
        })
    }
    

    【讨论】:

    • 有没有办法修改它以等待值更改而不是单击按钮?
    • 当然。获取值将更改的元素而不是按钮,然后将其更改为“更改”侦听器而不是单击侦听器。所以:const input = document.getElementById("my-input"); 然后将添加/删除侦听器更改为input.addEventListener("change", resolver)。但是,请注意,promise 将在第一个更改事件上解决,并且进一步的更改不会做任何事情。如果您希望代码在任何更改上运行,请将其放在事件侦听器本身中,而不是使用 Promise。
    • 为什么要先移除事件监听,然后再重新添加?
    • @CRice 谢谢。另外,我注意到您声明了buttonPromise,但后来将其称为clickPromise。这可能会让一些读者感到困惑。
    • @CRice 能否也解释一下移除事件监听器、返回并再次添加背后的逻辑?
    猜你喜欢
    • 2020-04-16
    • 2018-05-09
    • 2016-09-21
    • 2019-04-16
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多