如何“逃避”退货声明的范围?

时间:2012-08-19 08:55:53

标签: javascript function event-handling return

我需要设置一个事件处理程序,其作用是返回设置处理程序的函数,而不是匿名触发器处理程序本身。怎么能实现这一目标?请参阅以下代码:

if(subFormToServer())
    doSuccessDance();
else
    doErrorStuff();

function subFormToServer(thaGoods) {
  $('<iframe name="subform-target" style="display: none;"></iframe>')
    .bind('load',  function(){ return 0; }) // how to I "pass" these return statements "up" to my function or "escape" them, so to speak, so that what they're returning isn't the load/error handler functions, but actually the subFormToServer function?
    .bind('error', function(){ return 1; })
    .appendTo('body');

 $('<form method="POST" '+
          'action="http://server/formHandler.php" '+
          'target="subform-target"> '+

        '<input name=inputName              value="'+encodeURIComponent(thaGoods)+'">'+

    '</form>')[0]
    .submit();
}

1 个答案:

答案 0 :(得分:4)

这是不可能的。考虑这种情况,如果是:

// Assume form takes 10 seconds to respond
var x = subFormToServer(...)

// form has neither loaded nor errored yet - what does x contain?
alert(x)

你最好的选择是:

subFormToServer(thaGoods, doSuccessDance, doErrorStuff);

function subFormToServer(thaGoods, worked, didnt) {
    $('<iframe name="subform-target" style="display: none;"></iframe>')
        .on('load',  worked)
        .on('error', didnt)
        .appendTo('body');

    $('<form />', {
        method: "POST",
        action: "http://server/formHandler.php",
        target: "subform-target"
    }).append(
        $('<input />', {
            name: "inputName",
            value: encodeURIComponent(thaGoods)
        })
    ).submit()
}