3

我有一个场景,我希望在特定的第 3 方 js 函数完成执行后执行我的函数。

我无法编辑源代码,loadOne但是我可以添加/覆盖我newLoadOne的 as on click 监听器。所以我可以loadOne代表它执行并使用它返回的数据执行我的代码。

现在,我在方法的异步回调返回之前newLoadOne打印console.log 。loadOne

HTML

<select id="option1">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<select id="option2">
    <option>One</option>
    <option>Two</option>
    <option>Three</option>
</select>

<input id="submit" type="button" value="Submit" />  

JavaScript

function loadOne(){
    someAsyncXhrMethod(with_its_own_parameters);//its own xhr method with aync callbacks 
}


function newLoadOne(){

    (function(){loadOne(); console.log('done');}());
}

function optionschanged(){
    console.log('options changed');
}

function bEvents(){
    $('#option1').change(optionschanged);
    $('#option2').change(optionschanged);
    $('#submit').bind('click', newLoadOne); //this is where i replace the call to loadOne with my newLoadOne
}

$(document).ready(function () {
    console.log('ready');
    bEvents();

});

这是jsFiddle 链接- 注意:源代码中的 $.ajax 调用是为了解释该方法loadOne具有一些异步回调。所以$(document).ajaxComplete不是答案。

4

2 回答 2

2

您别无选择,只能轮询以查看异步方法是否已完成。check_some_async_xhr_method_completed据推测,它会以适当的频率改变您可以轮询的状态(我们称之为例程)。

function newLoadOne () {
    loadOne (); 
    check_completion (function (completed) {
        console.log (completed ? 'done' : 'never finished');
    });
}

function check_completion (callback) {
    var number_of_tries = 20;
    var timer = setInterval (
        function () {
            if (check_some_async_xhr_method_completed ()) {
                clearInterval (timer);
                callback (true);
            } else if (!number_of_tries--) {
                clearInterval (timer);
                callback (false);
            }
        },       
        500
    );
}

或者,如果您更喜欢使用 Promise:

function newLoadOne () {
    loadOne (); 
    check_completion ().then (
        function () {console.log ('done'),
        function () {console.log ('never finished')
    );
}    

function check_completion () {
    var promise = Promise.new();
    var number_of_tries = 20;
    var timer = setInterval (
        function () {
            if (check_some_async_xhr_method_completed ()) {
                clearInterval (timer);
                p.fulfill ();
            } else if(!number_of_tries--) {
                clearInterval (timer);
                p.reject ();
            }
        },       
        500
    );
    return promise;
}

或者,when库已经有一个处理轮询的例程。

于 2013-06-28T20:24:52.527 回答
0

在我看来,这会奏效......

$(document).ajaxComplete(function (event, xhr, settings) {
  if ( settings.url === "the/url/that/loadone/uses" ) {
    // do your callback here
  }
});

抱歉,这仅在使用 jQuery 发出请求时有效。

于 2013-06-22T19:11:04.503 回答