简体   繁体   English

通过 jQuery 单击按钮后如何调用回调 function?

[英]How to call a callback function after click on a button throgh jQuery?

I have a button that is saving data.我有一个保存数据的按钮。 I am trying to execute some line once button work is done.完成按钮工作后,我正在尝试执行某些行。

    function executionRequest(action, acting, data) {
        document.getElementById('vpl_ide_save').click();
        if (!data) {
          data = {};
        }
        if (!lastConsole.isConnected()) {
          VPL_Util.requestAction(action, '', data, options.ajaxurl)
            .done(function (response) {
              VPL_Util.webSocketMonitor(
                response,
                action,
                acting,
                executionActions
              );
            })
            .fail(showErrorMessage);
        }
      }

Can I call a callback function with我可以用

document.getElementById('vpl_ide_save').click()

so rest of the lines run after that only所以 rest 的线路仅在此之后运行

I know your question mentions callbacks, but promises might provide a better way to handle this asynchonous operation.我知道您的问题提到了回调,但承诺可能会提供一种更好的方式来处理这种异步操作。 This snippet has pretty comprehensive comments that should explain how you can implement this.这个片段有非常全面的评论,应该解释你如何实现它。

There are three main functions in the snippet.代码段中有三个主要功能 Execution requests are simulated by simulateExecutionRequest , which is responsible for calling asyncSave and then (assuming the save was successful) doExecutionRequest .执行请求由模拟执行请求simulateExecutionRequest ,它负责调用asyncSave然后(假设保存成功) doExecutionRequest

The magic happens in asyncSave , which returns a promise.魔术发生在asyncSave中,它返回 promise。 This lets simulateExecutionRequest wait until asyncSave is done and then call doExecutionRequest if the save was successful.这让simulateExecutionRequest等到asyncSave完成,然后在保存成功时调用doExecutionRequest Note that asyncSave is also the listener on the Save button (and since it is called directly by simulateExecutionRequest , there's no need to call the button's .click method programmatically).请注意, asyncSave也是Save按钮上的侦听器(并且由于它是由.click simulateExecutionRequest )。

The doExecutionRequest function is really just a placeholder for whatever you need to do after the save completes. doExecutionRequest function 实际上只是保存完成后您需要执行的任何操作的占位符。 (Right now, it just logs some hard-coded information.) (现在,它只记录一些硬编码信息。)

 const // Identifies some DOM elements input = document.getElementById("myInput"), saveBtn = document.getElementById("vpl_ide_save"), simulateBtn = document.getElementById("simulateBtn"), // Simulates saving some data (but is synchronous) save = function(){ const text = input.value; if(text){ console.log(`saved: '${text}'`); return text; // So we can know if it succeeded } } // Will call `asyncSave` when saveBtn is clicked saveBtn.addEventListener("click", asyncSave); // (IRL, execution requests probably happen programatically) simulateRequestBtn.addEventListener("click", simulateExecutionRequest); // Defines `asyncSave`, which creates and returns a promise. // The promise calls `save` asynchronously using setTimeout. // Because `asyncSave` returns a promise, our other code // can be delayed until after `save` has finished. // (This is called programatically as well as by user interaction) function asyncSave(event){ const promisedSave = new Promise( // Promise constructor takes an executor function // (which takes two functions that are used to provide // output once the promise is resolved or rejected) (resolve, reject) => { // Simulates a delay (because I/O is asynchronous) setTimeout(saveAndSettlePromise, 1500); // Calls `save`, then resolves or rejects promise function saveAndSettlePromise(){ if( save() ){ resolve("saved"); } else{ if(event){ console.log("save what?"); } reject("nothing to save"); } } } ); return promisedSave; } // This is what happens in response to an execution request function simulateExecutionRequest(){ // Calls `asyncSave` asyncSave().then( // If async save resolves, then this anonymous function runs (resolvedValue) => { // (The resolved value is available here if we want it) //Defines some variables const action_val = "log", acting_val = true, lastConsoleIsConnected = false; // Calls `doExecutionRequest` doExecutionRequest(action_val, acting_val); // Defines `doExecutionRequest` function (Demo version) function doExecutionRequest(action, acting, data = {}){ // `data = {}` makes `data` an optional parameter // Checks connection, and does something with data if (.lastConsoleIsConnected){ console:log(`execution request; 'data' has type '${typeof data}'`). } } } ),catch( // If `asyncSave` rejects. this runs instead (reason)=> console:log("request canceled; " + reason) ); }
 <label> Enter something to save: <input id="myInput" value="" /> </label> <div> <button id="vpl_ide_save">Save</button> </div> <hr /> <div> <button id="simulateRequestBtn">Simulate Request</button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM