简体   繁体   中英

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. 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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