如何使用Deferred重用$ .when()

时间:2014-10-17 21:49:07

标签: jquery jquery-deferred

我想重用一个jQuery Deferred。 HTML:

<form id="theForm" class="form-horizontal" action="" method="post">
    <div class="form-actions">
        <button type="submit" class="btn btn-primary">Do Something</button>
    </div>
</form>

使用Javascript:

var aDeferred = $.Deferred();

var doSomething = function () {
    console.log('in doSomething');
    aDeferred.resolve();
    console.log('state after resolving: ' + aDeferred.state());
}

$('#theForm').submit(function (event) {
    event.preventDefault();
    console.log('state in submit: ' + aDeferred.state());
    doSomething();
});

$.when(aDeferred).done(function () {
    console.log('we are done');
    aDeferred = $.Deferred();
});

- &GT; jsFidlle

第一次点击按钮时,我理解了序列:

state in submit: pending
in doSomething
we are done
state after resolving: pending 

但是在第一次点击后,虽然延期已经解决,但$.when().done()不再执行了。

state in submit: pending
in doSomething
state after resolving: resolved 

但是,如果我在提交功能中移动$.when(),它可以正常工作:

$('#theForm').submit(function (event) {
    event.preventDefault();
    console.log('state in submit: ' + aDeferred.state());
    doSomething();

    $.when(aDeferred).done(function () {
        console.log('we are done');
        aDeferred = $.Deferred();
    });
});

有人可以解释原因吗?

0 个答案:

没有答案