在“非ajax”函数上使用jquery

时间:2013-04-18 21:28:11

标签: javascript jquery jquery-deferred

我可以在“非ajax”函数上使用jquery done()吗?当我尝试做这样的事情时,我收到错误Uncaught TypeError: Cannot call method 'done' of undefined

function countThreeSeconds() {
    var counter = 0,
    timer = setInterval(function () {

        if (counter == 3) {
            console.log("All done. That was three seconds.");
            window.clearInterval(timer);

        } else {
          console.log("Not there yet. Counter at: " + counter);
        }
        counter++;
    }, 1000);

}

(function(){
  var timer = countThreeSeconds().done(function(){
     alert("done");
  });

}());

由于

JSBIN

3 个答案:

答案 0 :(得分:14)

使非ajax函数返回一个promise对象。

function countThreeSeconds() {
    var counter = 0,
    deferred = $.Deferred(),
    timer = setInterval(function () {

        if (counter == 3) {
            console.log("All done. That was three seconds.");
            window.clearInterval(timer);
            deferred.resolve();

        } else {              
            console.log("Not there yet. Counter at: " + counter);
            deferred.notify(counter);
        }
        counter++;
    }, 1000);
    return deferred.promise();

}

(function(){
  var timer = countThreeSeconds().done(function(){
     alert("done");
  }).progress(function(i){
     console.log("in progress...",i);
  });

}());

答案 1 :(得分:2)

由于您没有从函数返回任何内容,因此它是完全有效的JS行为。为了能够在函数上使用done,请从中返回jQuery.Deferred个对象。

这样的事情:

function countThreeSeconds() {
    var defer = $.Deferred(function() { // do your stuff here });
    return defer.promise();
}

答案 2 :(得分:1)

托马斯,有这样的事情,你可以让Deferred对象(及其承诺)真的适合你。

例如,您可以使countThreeSeconds()成为原始的,更通用的函数,并在调用函数中执行所有进度/完成报告。

function countSeconds(n) {
    var dfrd = $.Deferred(),
        counter = 0,
        timer = setInterval(function() {
            counter++;
            if (counter < n) { dfrd.notify(counter); }
            else { dfrd.resolve(); }
        }, 1000);
    return {
        promise: dfrd.promise(),
        timer: timer
    };
}

(function() {
    var timerObj = countSeconds(3);
    timerObj.promise.progress(function(counter) {
        console.log("Not there yet. Counter at: " + counter);
    }).done(function() {
        clearInterval(timerObj.timer);
        console.log("All done. That was three seconds.");
        alert("done");
    });
}());

因此,另一个函数可以使用不同的值调用countSeconds(),并以不同的方式处理进度和完成情况。

例如:

(function() {
    var timerObj = countSeconds(10);
    timerObj.promise.progress(function(counter) {
        $("#message").text("Counter = " + counter);
    }).done(function() {
        clearInterval(timerObj.timer);
        $("#message").text('Complete');
    });
}());