简体   繁体   English

使用CallBack进行Jquery自定义功能

[英]Jquery custom function with CallBack

I have the following function: 我有以下功能:

Test.prototype.showToken = function () {
         $('#modal').modal('show');

         $('#modal').find('#btnOk').click(function (e) {
             // here I want to callback
             var returnValue = '123';
         });

     $('#modal').find('#btnProcess').click(function (e) {
             // here I want to callback cancel
             var returnValue = '456';
         });
     },

Now I have this in other function: 现在我在其他功能中有这个:

$.Test.showToken();

This works fine... Now I want inside my showToken to have a CallBack so when the click button happens I get in my other function the callback triggered. 这工作正常...现在我想在我的showToken里面有一个CallBack所以当点击按钮发生时,我进入我的其他功能,触发了回调。 For example: 例如:

$.Test.showToken(function(e){

   // here would like to get the trigger when the btnOK is clicked and also be able to get the returnValue.

   // here would like to get the trigger when the btnProcess is clicked and also be able to get the returnValue.

});

Any clue? 任何线索?

You can accept callback functions in your function arguments. 您可以在函数参数中接受回调函数。

Test.prototype.showToken = function (options) {
   $('#modal').modal('show');

   $('#modal').find('#btnOk').click(options.okButtonCallback);

   $('#modal').find('#btnProcess').click(options.processButtonCallback);
}

Then when you call your function, you can pass callbacks to do special things. 然后当你调用你的函数时,你可以通过回调来做特殊的事情。

$.Test.showToken({okButtonCallback: function(){
   // This will run on the ok button press.
}, processButtonCallback: function(){
   // This will run on the process button press.
}});

Is this what you want? 这是你想要的吗?

Test.prototype.showToken = function (okCallback, processCallback) {
         $('#modal').modal('show');

         $('#modal').find('#btnOk').click(function (e) {
             // here I want to callback
             var returnValue= ???
             okCallback(returnValue)
         });

     $('#modal').find('#btnProcess').click(function (e) {
             // here I want to callback cancel
             processCallback()
         });
     },
/// ...

/// Usage:

Test.showToken(function(retValFromOk){ 
   // from OK
   console.log("From ok", retValFromOk);
}, function() {
   // from process
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM