Is it possible that the return of the JS function is dependent on user action?

Is it possible that returning a JS function depends on user action?

So let's say I have function a and function b.

The b function invokes a two-button dialog that returns true and returns false. Can I call b from a and make a wait for a return from b before continuing?

Code example:

function a(){ if(b()){ do x }else{ do y } } function b(){ $("#anElement").dialog({ title: "This is a Dialog", buttons:{ "Yes": function(){ //do some stuff $(this).dialog("close"); return true; }, Cancel: function(){ //do some stuff $(this).dialog("close"); return false; } } }); } 

I think this is very similar to confirmation, but I want to build more than just yes / no. Any suggestions?

+4
source share
2 answers

No, you cannot stop the execution of the function (well, you could with an infinite while loop with a break condition, but this is a terrible practice). However, you can split A into two functions and call the second half of function A from function B. You can even pass the return function to function B and call it by passing the value of the user action.

Example:

 function A() { // do stuff B(finishA); } function B(callback) { if(someCondition) { callback(true); } else { callback(false); } } function finishA(userInput) { if(userInput) { // do something if the user clicked okay } else { // do something if the user clicked cancel } } 
+2
source

One solution will be ...

 function a () { b( function () { // do x }, function () { // do y }); } function b ( fn1, fn2 ) { $( "#anElement" ).dialog({ title: "This is a Dialog", buttons: { "Yes": function () { //do some stuff $( this ).dialog( "close" ); fn1(); }, "Cancel": function () { //do some stuff $( this ).dialog( "close" ); fn2(); } } }); } 

So you pass two functions to b . The first is activated if the "Yes" button is activated, and the second function is activated if the "Cancel" button is activated.

This pattern allows you to define behavior directly inside function a instead of adding it to function b .

+1
source

Source: https://habr.com/ru/post/1411323/


All Articles