使用onload回调?

时间:2013-05-16 12:41:44

标签: javascript

一旦这个函数返回一个回调,我想触发一个新函数。这显示在这里:Create a custom callback in JavaScript我该怎么做?

function loadImg (imgSrc, callback) {
    var newImg = new Image();
    newImg.onload = function() {
        var height = newImg.height;
        var width = newImg.width;
        if(height > width){
            console.log(false);
            if(callback) callback(false);
        } else {
            console.log(true);
            if(callback) callback(true);
        }
     }
     newImg.onerror = function () {
         if(callback) callback('error');
     }
     newImg.src = imgSrc;
}

1 个答案:

答案 0 :(得分:0)

正如已经说过的那样,当你检查它时,你已经在调用你的回调......然后再打电话给它:

if(callback) callback(false);

运行此代码(jsFiddle链接在底部)。它与您的代码的概念相同。

function doMe(something, callback) {
    console.log("Congrats, I did " + something);  
    if(callback) {
       callback();   
    }
}

doMe("the disco", function() {
   console.log("I'm a callback"); 
});
//I'm a callback

jsFiddle

或者,您可以使它更“文字”并使用call()方法传递您的参数:

function doMe(something, callback) {
    console.log("Congrats, I did " + something);  
    if(callback) {
       callback.call(this, true);   
    }
}

doMe("the disco", function(bool) {
   console.log("I'm a callback. " + bool + " story"); 
});
// I'm a callback. true story

another fiddle