I am making some SPA app. When app is running at some point i start one method. Some code in there give me boolean. I would like to stop method when is 'half executed' and that boolean is false. I need something like break for loop, but that might work with methods. It is possible ?
Thanks for answers.
if(el === 'work'){
if(!actions.authentication()){
// That code is in another method. I want break that with some code placed here.
}
}
It's kinda obvious and you almost answered yourself, but you can use return ...
if(el === "work") {
if(actions.authentication() == false) {
return
}
}
Related
I need to run through a stack of HTML Elements. But all my attempts to write a recursive function didn't work.
In the snippet below I cannot return value from if statement and afterwards from a function itself.
I can console.log the information I need, it gets there, but trying to return it, it doesn't work.
I never had such an issue with returning some data that's why I decided to display it here so as to let a fresh-eye to revise the code.
function findElementByDataValue(target: EventTarget, data: {key: string, value: string}){
if (target.dataset[data.key] === data.value) {
return target;
};
if (target.children.length > 0) {
for (const child in target.children) {
const element = target.children[child];
// I tried to return "recursive" function here too. "Return" Abrupt execution (as it should)
if (element.children && typeof element === 'object') {
findElementByDataValue(element, data);
}
}
}
}
if you have any ideas or noticed an issue with my recursive function, I would appreciate any help.
Using the return keyword like you are doing.
Your second function calls the first function without returning the value returned by the first function:
Replace
if (element.children && typeof element === 'object') {
findElementByDataValue(element, data);
}
with:
if (element.children && typeof element === 'object') {
return findElementByDataValue(element, data);
}
In general, run your code in a debugger (popular web browsers provide debuggers) to see what is going on.
See some debuggers documentation:
https://developer.mozilla.org/en-US/docs/Tools/Debugger
https://developers.google.com/web/tools/chrome-devtools/javascript/
If you are new to JavaScript, I suggest looking into unit testing and test-driven development.
Writing tests (early) will help you think of what can go wrong with your code and write more robust functions. Jasmine is nice, this article suggests many other JavaScript unit testing options
So I recently decided to start learning JavaScript. I come from only knowing VB.NET for programming knowledge and HTML & CSS for design. Anyway, scrap.tf is a website for TF2 banking which makes things automatic. I am planning to write a basic Chrome plugin, and I want to be able to if the button is clicked, this function will happen. I've got this all set up but when the button's clicked, it only takes me to scrap.tf/hats, EnQueueHatBank(); is the JS command they use there to join the queue. This even never fires unless I type it in after I'm on the site. Do I need to wait for it to fire?
if (location.href === 'http://scrap.tf/hats')
{
EnQueueHatBank();
}
else
{
window.location.href='http://scrap.tf/hats';
EnQueueHatBank();
}
You need to correct the comparison to use two equal signs.
if (location.href == 'http://www.scrap.tf/hats')
{
EnQueueHatBank();
}
Once you end up with tools like jslint, javascript even offers a === operator, which does type checking, too (checks if both sides are strings, as in this example).
I think this talk of = vs == is missing the point. You're changing window.location before you call EnQueueHatBank, so you navigate to a new page before the function is ever called. That's what's stopping it from running. So the first thing you need to do is:
Call EnQueueHatBank first.
if (location.href === 'http://www.scrap.tf/hats') {
EnQueueHatBank();
} else {
EnQueueHatBank();
window.location.href='http://www.scrap.tf/hats';
}
Clean up the code a little, because the structure is a little awkward. You're calling EnQueueHatBank either way, so there's no need for it to be in the if statement:
EnQueueHatBank();
if (window.location.href !== 'http://www.scrap.tf/hats') {
window.location.href = 'http://www.scrap.tf/hats';
}
Finally, remember that http://www.scrap.tf/hats/ probably goes to the same place as http://www.scrap.tf/hats, not to mention https://www.scrap.tf/hats?foo=bar and so forth. You'd be better off with a less-strict test:
EnQueueHatBank();
if (window.location.href.indexOf('://www.scrap.tf/hats') > -1) {
window.location.href = 'http://www.scrap.tf/hats';
}
EDIT: Based on your comment, you will need to do this:
if (window.location.href.indexOf('://www.scrap.tf/hats') > -1) {
EnQueueHatBank();
}
else {
window.location.href = 'http://www.scrap.tf/hats';
}
This will only work if your program runs again after navigating to scrap.tf/hats, so make sure it runs every time you load a new page.
For security reasons, you cannot initiate code on one page and have it continue after you've navigated somewhere else. You'll have to call EnQueueHatBank from the page it's meant to run on.
You should use comparison === operation, but you did an value assignment =.
if (location.href === 'http://www.scrap.tf/hats')
{
EnQueueHatBank();
}
else
{
window.location.href='http://www.scrap.tf/hats';
EnQueueHatBank();
}
I wrote this simple function once, to display notifications on hash change :
function watchHash() {
if(location.hash == '#thanks') {
displayNotification('Thanks for your feedback, I\'ll try to get back to you as soon as possible.'); // Notify on form submit success
}
if(location.hash == '#error') {
displayNotification('Oops, something went wrong ! Please try again.'); // Notify on form submit error
}
}
window.onhashchange = watchHash;
I came back to it today and I thought, is it correct if I write it this way instead?
function watchHash() {
if(location.hash == '#thanks') {
displayNotification('Thanks for your feedback, I\'ll try to get back to you as soon as possible.'); // Notify on form submit success
}
else if(location.hash == '#error') {
displayNotification('Oops, something went wrong ! Please try again.'); // Notify on form submit error
}
else {
return;
}
}
window.onhashchange = watchHash;
If so, is it relevant?
I'm a bit confused here, I'd like to stick to best practices.
Thanks for your help.
The second scenario is much better. Why?
Because in the first scenario if first condition is met or not met - it doesn't matter, the second case is checked too, the third, the fourth and so on.
In second case If the first case fails, then the second one is tested, if it fails, the third is tested, so your software does not spend useless time checking scenario which will not happen.
In your case, either method works just as well. However, there are some times when using the else clause is truly the best way to handle over-lapping logic.
Untested p-code, just for an example
if (isRaining) && (iHaveUmbrella) {
iGetWet = false;
} else if (isRaining) {
iGetWet = true;
} else {
iGetWet = false;
}
In this case, the else if means that if the first condition is true, the second condition is never checked.
it might not be relevant for this usecase, but the 1st way is slower because the interpreter has to check conditions more often.. consider a game loop which is called 60 times per second and you don't structure your if else blocks you will get a huge performance hit.
Either way works properly. Differences between two are readability and pattern of coding.
Regarding readability, I personally prefer the first way to work on a single input. Second one works in better performance, but you might lost in multiple boundaries if you're not proficient developer.
Regarding pattern of coding, we can see that the first one won't return anything. Second one will return null ONLY IF hash tag is neither your selections. You can't use this function to check the condition because it won't return when hash tag is either '#thanks' or '#error'.
Your second version is "correct" insomuch as its functionality is identical to the first version, but the added code is entirely redundant.
In my phone-gap index.html javascript part, window.refresh is to be used for IOS and this.refresh for android. I want to use the same index.html for both. Through (navigator.userAgent.toLowerCase().match(), i can distinguish between IOS and android, but i don't want to apply this condition every time window. or this. is to be used. Can i apply this condition globally and assign value to a variable viz. 'this' for android and 'window' for IOS and then use that variable wherever required. Is this kind of a thing possible or any workaround so that multiple if -else statements can be avoided.
Any suggestions are most welcome.
Thanks in advance.
You could just try if this.refresh exists and call it. If its undefined you can fallback to window.refresh. Code example:
if(this.refresh === undefined) {
window.refresh();
} else {
this.refresh();
}
I'm not sure which way it would make the most sense, but I hope you get the concept: if something is undefined, you can't call it and need to figure out something else.
extending jsalonen answer
<script>
function browserRefresh()
{
if(this.refresh === undefined) {
window.refresh();
} else {
this.refresh();
}
}
</script>
and when ever you want to refresh just call
browserRefresh();
The other day I posted about a Flash/Javascript issue I was having. Please see this:
Issues with javascript properly loading and seeing everything
I know how I want to fix it, but I am not in any way shape or form familiar with actionscript. I have avoided adobe products like the plague from when I was developing myself since it costs a fortune to buy and of their products, but big employers love it and pay for it so here I am. Our "Flash" guy just left the team and I inherited this issue. If you read my other post you know what is going on so I will move on. I want to make a simple call from actionscript to my javascript taht is referenced in my other post. I specifically want to call the CheckboxCollection function from inside of actionscript. I don't need to pass it any args or anything of the such from inside of actionscript. All I need it to do is run that function once the flash is done loading. The javascript function will take care of everything I need, I just HAVE TO HAVE IT called from actionscript to make everything work in harmony. I am in the middle of teaching myself all things adobe and actionscript(much to my dismay), but I really have no clue where top go from here to make this work. I have reviewed adobe documentation, but until I have a better grasp of the language as a whole I am still lost. I copied most of my actionscript on to here, but I did leave out everything that had to deal with mouseover events, since my issue is not about a mouseover and they all work like a charm. Thanks in advance!
-------------------------------------------------------------------------------------------UPDATE: I had to stop working on this to get some other things done, but I am back to step one. NO matter what I do I am having no luck making this work. I have tried all suggestions on here, and tried everything I KNOW how to do, but I am having no luck. If anyone could take a look at this post and the one that I link to (It is the companion javascript for this) and see if they can come up with anything. I have tried so many different iterations of my code there is no use putting all of my trials up for example of what doesn't work, Thanks Everyone!
/*
JavaScript External Calls
*/
function RegisterExternalCalls():void
{
if(ExternalInterface.available)
ExternalInterface.addCallback("HighlightWheel", HighlightWheel);
}
function HighlightWheel($args:String,$show:String,...arguments):void
{
$args = $args == "financial"?"center":$args;
var _obj:Object = ObjectCollection[$args].Objects.Click;
if(ObjectCollection[$args].Objects.currentObject.name.toLowerCase() == "center")
{
bcenter = true;
_obj = ObjectCollection[$args].Objects.currentObject.getChildByName("financialBtn");
}
if(CBool($show))
{
if(arguments.length > 0 && arguments[0] == "TITLE") // || $args == "center")
_obj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER));
else
{
if(ObjectCollection[$args].labels.Label.toUpperCase() === "CENTER")
{
ObjectCollection["income"].Objects.Click.gotoAndPlay(2);
ObjectCollection["property"].Objects.Click.gotoAndPlay(2);
ObjectCollection["education"].Objects.Click.gotoAndPlay(2);
ObjectCollection["health"].Objects.Click.gotoAndPlay(2);
ObjectCollection["retirement"].Objects.Click.gotoAndPlay(2);
}
else
{
_obj.gotoAndPlay(2);
}
}
}
else
{
if(arguments.length > 0 && arguments[0] == "TITLE")
_obj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT));
else
{
if(ObjectCollection[$args].labels.Label.toUpperCase() === "CENTER")
{
ObjectCollection["income"].Objects.Click.gotoAndPlay(11);
ObjectCollection["property"].Objects.Click.gotoAndPlay(11);
ObjectCollection["education"].Objects.Click.gotoAndPlay(11);
ObjectCollection["health"].Objects.Click.gotoAndPlay(11);
ObjectCollection["retirement"].Objects.Click.gotoAndPlay(11);
}
else
{
_obj.gotoAndPlay(11);
}
}
}
}
function CallExternalFunction($label:String,$show:Boolean = true):void
{
var lbl:String = $label.toLowerCase().indexOf("btn") > -1?"financialTitle":$label + "Title";
if(ExternalInterface.available)
ExternalInterface.call("COUNTRY.Financial.highlightProductGroup",lbl,$show);
}
function CBool($value:String):Boolean
{
if($value == "true")
return true;
else
return false;
}
function PrintSetup($evt:MouseEvent):void
{
var pjob:PrintJob = new PrintJob();
if(pjob.start())
{
pjob.addPage(wheel);
pjob.send();
}
}
I believe you do this through ExternalInterface.call and pass the javascript function that should be called, like so:
ExternalInterface.call( "CheckboxCollection" )
If you need to pass arguments:
ExternalInterface.call( "CheckboxCollection", value1, value2 )
For more information here is the documentation
If in your JS you don't need necessarily this:
var CheckboxCollection = function()
try to change it to this:
function CheckboxCollection()
even if it seems (if the JS is still the same) you have anything nested. Maybe you can try too call it this way to (but I never tried anything similar):
ExternalInterface.call("SOME.PLACE.QuoteRequest.CheckboxCollection");