Stop subsequent methods call of onclick - javascript

If this is problem already existed then please help me mark it as duplicate cause I cannot find the similar solution.
While having multiple methods call on onclick attribute, for example:
<a onclick="foo();afterFoo();afterAfterFoo();"/>
I want to stop subsequent calls like afterFoo() , afterAfterFoo(); when foo() meets some condition.
I tried return false; in method foo() but it still calls other methods. I remember this trick used to work as expected.

It doesn't happen that way. You need to create a wrapping function and attach it as onClick handler rather than call the 3 functions from it directly. You may call your 3 functions from the wrapping function based on the if conditions.
<a onclick="clickHandler();"/>
function clickHandler() {
foo() && afterFoo() && afterAfterFoo();
}

You can do it simply by using ifconditions:
function foo() {
console.log('foo')
return true;
}
function afterFoo() {
console.log('afterFoo')
return false;
}
function afterAfterFoo() {
console.log('afterAfterFoo')
return true;
}
function specialSequence() {
if (foo())
if (afterFoo())
afterAfterFoo();
}
<a onclick="specialSequence();">Click Me</a>
So what happens here:
we are calling specialSequence. It runs foo and if it returns true, we continue to the next sequence function afterFoo, and if this returns true we continue to afterAfterFoo. But it returns false, which means that after running afterFoo the function specialSequence will stop running.
After you stated that there are several parameters to each function and you don't want specialSequence to have the sum of parameters of all the functions its using, You can just use it in the html like this (simply copy the function to the onClick)
function foo() {
console.log('foo')
return true;
}
function afterFoo() {
console.log('afterFoo')
return false;
}
function afterAfterFoo() {
console.log('afterAfterFoo')
return true;
}
<a onclick="if (foo())
if (afterFoo())
afterAfterFoo();">Click Me</a>

Related

how to avoid repeating return false line

On many functions I have this line:
if (!$('.postitle').hasClass('pmarked')) {return false;}
To avoid repeating it so often I tried this:
function falsea(){
if (!$('.postitle').hasClass('pmarked')) {return false;}
}
and then call the above - falsea() instead of if (!$('.postitle')...
It doesn't work.
Is there any simillar way to avoid repeating entire line each time ?
The level is incorrect.
return false actually do nothing but stop your function for further running.
If you are not outputing any result, this is just same as simply write return.
So in your falsea() function, your return false stop the function, not the outer one but the falsea() itself, it won't make the mother do anything.
What you can do is
function falsea(){
return $('.postitle').hasClass('pmarked'))
}
In mother,
if (!falsea()) return
It doesn't work.
It doesn't work because that's not how functions work (in any language, really). A return statement in the callee doesn't cause the caller to terminate. Simple example:
function foo() {
console.log('before bar()');
bar();
console.log('after bar()');
}
function bar() {
console.log('in bar; before return');
return false;
console.log('in bar; after return');
}
foo();
What you can do is put the condition in its own function to reuse that, but you still need an if statement in every caller:
function hasPmarked(){
return $('.postitle').hasClass('pmarked');
}
// in caller
if (!hasPmarked()) {
return false;
}
Is there any simillar way to avoid repeating entire line each time ?
You could create a function that accepts a callback and only executes the callback if the check succeeds.
For example:
function doStuffIfPMarked(stuff) {
if ($('.postitle').hasClass('pmarked')) {
stuff();
}
}
Then the caller can do:
doStuffIfPMarked(function() {
// do something
});
I.e. if you had this before:
function foo() {
if (!$('.postitle').hasClass('pmarked')) {return false;}
// do my stuff
}
you would write
function foo() {
doStuffIfPMarked(function() {
// do my stuff
});
}
You still need to repeat some code, but you are abstracting the condition logic away.
Your function will only return false or undefined.
Try adding at the end
return true;
Or even simpler, just do:
return !$('.postitle').hasClass('pmarked')
Keep in mind that the return doesn't propogate so you will still need check the return value of this function and return.
if (falsea()) {return false;}

Check if function returns true to execute another function

I have written a form validation using JS which ends with return(true);
function check() {
....validation code
return(true);
}
All I want is, need to check if check() function returns true, I want to execute another function.
Code I have tried is as follows:
if(check() === true) {
function() {
//Another function code
}
}
You should use return true; and your if statement doesn't need the === true comparison.
function check() {
//validation code
return true;
}
if(check()) {
//Another function code
}
JSFIDDLE
First of all, return is not a function, you can just do this:
return true;
Now, to only execute myFunction if check returns true, you can do this:
check() && myFunction()
This is shorthand for:
if(check()){
myFunction();
}
You don't need to compare the return value of check with true. It's already an boolean.
Now, instead of myFunction(), you can have any JavaScript code in that if statement. If you actually want to use, for example, myFunction, you have to make sure you've defined it somewhere, first:
function myFunction() {
// Do stuff...
}
You just need to modify your first code snippet. return is a keyword, what you are trying to do is to execute it as a function.
function check() {
....validation code
return true;
}
You'll need to change your 2nd snippet slightly, to execute the function too however... The simplest way is to wrap it as an anonymous function using curly braces:
if(check()) {
(function() {
//Another function code
})();
}
You're not calling the function in your affirmative clause, only declaring it. To call an anonymous function do this:
(function (){...})()
You could type
$this.myFunction=function(){
//code here
}
and to execute some code if a the myFunction function is true, you could use booleans
such as e.g.
if(//your function is true){
and so on

call to a function that inside another function in JavaScript

I want to call a function that is in another function.
example for the functions:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
}
I need to call to funcTwo function, when I click on a button which is outside of these two functions
how can i do it?
No, You can't call unless you return that function.
Function2 is private to function1.
you use
function funcOne() {
return {
funcTwo :function() { // i want to call to this function
//do something
}
}
}
EDIT: Structuring code
function funcOne() {
var funcTwo = function() { // private function
//do something
}
return {
funcTwo : funcTwo
}
}
Now you can call it as:
funcOne().funcTwo()
As you have it defined in your example, you can't. funcTwo is scoped inside of funcOne, so it can only be called from inside funcOne. You can assign funcTwo to a variable that is scoped outside of funcOne and that would work:
var funcRef;
function funcOne() {
funcRef = function funcTwo() {
}
}
In this case, funcRef would hold a reference and could be used, but that reference is only set once funcOne has been executed.
Reading some Douglas Crockford may help you understand...
Try recoding as:
function funcOne() {
this.funcTwo = function() {
}
}
I think you'd have to declare an instance of a funcOne object and then call the funcTwo method of that object. I'm a bit busy at the moment so I can't refine this answer at the moment.
It is not possible as the second function will be created just when the first function is called. it is not existent prior to that.
You would have to define it outside the first function like so:
function funcOne() {
}
function funcTwo() { // i want to call to this function
//do something
}
Or you could also call the first function and return the second function like this:
function funcOne() {
function funcTwo() { // i want to call to this function
//do something
}
return functTwo;
}
And then call it like this:
var f = funcOne();
f();

Template method pattern with setTimeout in JavaScript

I have a close function that will close some instance. The class that includes the function allows derived classes to override close. Here, I want to make sure that close always calls dispose even in derived classes. I achieve this by the following.
function close() {
closeCore();
dispose();
}
function closeCore() {
// derived class can override this method.
}
This works fine, but I have one case where I want to perform CSS animation before I dispose the instance. This is what I do.
function close () {
instance.classList.add("fancy-animation-that-takes-800ms");
setTimeout(function () {
dispose();
},800);
}
But as soon as I do this, the template pattern I use cannot be applied. Is there a way to make sure the close function always call dispose in the second example?
You might have close expect an object be returned from closeCore which had parameters like these:
return {timeout: 800, callback: function () {/*....will execute after a timeout..*/}};
or:
return {callback: function () { /*...will be immediately executed...*/}};
or:
return function () { /*...will be immediately executed...*/};
...and then call their timeout for them (if any), and then after your timeout executed their callback, then call dispose for them.
The relevant part of your close code might look like:
function close() {
var ccObj = closeCore();
var ccIsObj = ccObj && typeof ccObj === 'object';
var callback = typeof ccObj === 'function' ? ccObj : (ccIsObj ? ccObj.callback : null);
if (ccIsObj && ccObj.timeout) {
if (!callback) {
throw 'You must implement a callback when supplying a timeout';
}
setTimeout(function () {
callback();
dispose();
}, ccObj.timeout);
}
else {
if (callback) {callback();}
dispose();
}
}
But if you want to allow the user to make arbitrary asynchronous calls of their own (such as Ajax), while you could instead allow the returning of a promise to which you added the dispose call, you wouldn't have a guarantee that the deriver would ensure the promise completed. You could automatically cancel the promise after a certain period of time, but you couldn't magically know when the deriving code was meant to finish unless again you abstracted this.

iOS return values to the asynchronous javascript calls

Below shown is js code which makes call to the native functions in iOS and Android, this function is called from another js method.Since the js calls to this function is asynchronous.we could not return any values in iOS.but in Android we could return the values without any issue.In iOS control dosent wait until i get the response.Actually we are not suppose to modify this function call otherwise we can pass a callback method from the caller function.Please help me to solve this issue
VestaPhoneBridge.IsAvailable = function(featureName)
{
if(isAndroid()) {
if(typeof VestaJavascriptInterface !== 'undefined')
{
return VestaJavascriptInterface.isAvailable(featureName);
}
return false;
}
else {
bridge.callHandler('initiateIsAvailableFunction',featureName,function(response) {
return response;
})
}
};
I assume you're talking about this line.
bridge.callHandler('initiateIsAvailableFunction',featureName,function(response) {
return response;
})
The problem will most likely be your return. The anonymous function you are passing as a callback will be called whenever the async request is finished. This means that it will be called by something inside the callHandler code path.
Your function is then returning to that function, and not the VestaPhoneBridge.IsAvailable function. Your callback should set values, and perform changes instead of returning a value.
Example
function Foo(callback) {
callback(); // 42 is returned here, but not assigned to anything!
}
function Bar() {
var baz = Foo(function() {
// You want to return 42. But here you are in a totally different function
// scope! You are in the anonymous function's scope, not Bar, so you are not
// returning anything to the caller of Bar().
return 42;
}
alert(baz); // Foo doesn't return anything, so this is undefined!
}
alert(Bar()); // This is also undefined, nothing was returned.

Categories

Resources