如何使函数在这种情况下返回一个值

时间:2014-01-10 08:24:17

标签: javascript jquery

我想像这样使用ui.confirm

if(ui.confirm('content')){
    //do something
}else{
    //do something
}

ui:

var ui = {
    confirm:function(content){
        //...            
        $(".btn-success").click(function(){
            //when I click this button , ui.confirm return true
        });
        $(".btn-warning").click(function(){
            //when I click this button , ui.confirm return false
        });
    }
}

虽然我还有另外一个不完整的解决方案:

var ui = {
    confirm:function(content,callback1,callback2){
        //...

        $(".btn-success").click(function(){
            //execute callback1
        });
        $(".btn-warning").click(function(){
            //execute callback2
        });
    }
}

3 个答案:

答案 0 :(得分:2)

无法使用异步功能

你需要做类似的事情:

ui.confirm('content', function() {
    //do something
}, function() {
    //do something
});

答案 1 :(得分:2)

您无法从confirm返回有意义的值,因为按钮点击是异步。这意味着按钮点击将(可能)“在将来的某个时刻”发生,但该功能必须“立即返回”。

JavaScript中的解决方案是在遇到这种情况时彻底使用异步编程模型。虽然callbacks是这种异步操作的构建块,但我更愿意在可能时使用Promise。

因此,因为dystroy不认为我应该;-),我将使用Promises/A提出一种方法(jQuery 1.9 + Deferred Objects工作正常用jQuery来“免费”。

function uiConfirm (msg) {
   var action = $.Deferred();

   // Note: On the button clicks the dialog should be closed as a Promise can only
   // be resolved/rejected once; Promises are really good for execution flow
   // management (see `then`), but are not as general as simple callbacks.
   $(".btn-success").click(function(){
       action.resolve("okay");
   });
   $(".btn-warning").click(function(){
       // Depending upon semantics, this could `reject` the Promise, but I think
       // it's cleaner to just resolve it with a different discriminator value 
       // in this case.
       action.resolve("cancel");
   });

   // uiConfirm returns immediately (before the clicks),
   // but returns a Promise/Deferred that can be resolved (or rejected) later
   // in response to a button click.
   return action;
}

uiConfirm("Do you like Cheese?")
   .then(function (value) {
      // This code runs when a button has been clicked
      alert("Action: " + value);
   });

// This code runs right after uiConfirm returns (before any clicks)
// because uiConfirm is asynchronous or "non-blocking"

答案 2 :(得分:1)

你不能完全这样做。当任何一个点击事件发生时,你必须提供一个回调函数来“做某事”。您无法从这些事件“返回”到先前执行的状态。

var ui = {
    confirm:function(content,callback1,callback2){
        $(".btn-success").click(function(){
            callback1();
        });
        $(".btn-warning").click(function(){
            callback2();
        });
    }
}

ui.confirm('content', function() {
  //do something
  alert("success");
}, function() {
  //do something else
  alert("WARNING");
})

示例:http://jsfiddle.net/xvbL5/1/