Javascript sequential execution after trigger - javascript

I'm having trouble with the way javascript execute the code (async)
I have this small piece of code that will trigger events and check the value of 'valid'.
My problem is that 'valid' is always true when entering the if statement because the events have not finished processing yet :
valid = true;
$(this).find('input').trigger('blur');
//valid will be modified in the triggered events
if(valid){
//Do something
}
So I'd like to wait till the events are finished to enter the statement, but trigger doesn't take a callback
I have seen some questions about this already solved but I didn't understand them and how to implement them.
What should I use to solve this ?

Thanks to JamesThorpe I found the answer I was looking for :
valid = true;
$.when($(this).find('input').trigger('blur')).done(function(){
if(valid){
//Do something
}
});
And now the if statement only gets executed after the events are triggered

As you want to have it triggered on blur, you can do it like this:
$(this).find('input').on('blur', function(){
if(valid){
//Do something
}
});
Note that the function will be triggered on all blur events. To have it only once use .one()

I don't understand why you are using trigger. I think you can directly use blur event:
$(this).find('input').blur(function(){
if(valid)
//do something
});

Related

Bug or i do a mistake with inboxsdk "presending" event

When i use the inboxSDK with the newGmail I face an issue that the "event" did not get the composeView like the other events.
sdk.Compose.registerComposeViewHandler(function (composeView) {
composeView.on("presending", function (event) {
// Only get event.cancel();
});
}
Did i do something wrong or it's a bug with the new Gmail UI ?
As of the documentation the presending callbacks event object only has the cancel method attached. And actually that is no problem at all since you already have the composeView availbale from the registerComposeViewHandlers scope. Just access that composeView object.
sdk.Compose.registerComposeViewHandler(function (composeView ) {
composeView.on("presending", function (event) {
console.log(composeView);
});
}
If the presending event triggers you can just use event.cancel() to stop the sending, do whatever you wanna do on the composeView like you would for example in the registerComposeViewHandler callback and when you're done do composeView.send() to finally send the email. Just make sure to have a condition for the cancel event so you actually be able to send at one point and not get stuck in the presend event forever.

How to handle nested event listeners javascript? (not about nested html elements)

I need a function to trigger only after 2 events.
First event is onload, and second is onmessage coming from an iframe.
If onload and onmessage=="something"=> trigger that.
Otherwise => something else.
However, it seems that onload is executed before my onmessage. SO i need the 2 event to be nested. (Or not?)
Shoud I do like this:
document.getElementById("myiframe").addEventListener("load", iframeLoaded, false);
function iframeLoaded(){
window.top.addEventListener("message", WhatisTheMessage, false);
}
function WhatisTheMessage(event){
window.top.removeEventListener("message", WhatisTheMessage, false);
if(event.date=="something"){//do something}
else if(event.date=="somethingelse"){//do somethingelse}
}
Does it seem correct? The problem that appear to me is that if "message" is arriving before (I think it is not is not possible), I don't listen to it.
window.addEventlistener("load",test,false);
window.addEventlistener("message",test,false);
var counter=0;
function test(event){
counter++;
if(counter==2){
//two event listeners called
}
}

How do you get JQuery to wait until a previous event has fired

I am having a list of divs,whenever I click them I call a function,some trigger other ajax functions.
Now while the click even fires an ajax event,if I click another div I get last clicked div function called.How to solve this.
document.addEventListener("click",function(event){
checkparent(event);
}
function checkpaternt(event){
if(($(event.target).class=="checkparent"){//call ajax functions
}
else {//call local functions}
later I check the class name of the target and call different functions.
some more info(there are lots of div elements and if else statements)
Thank you.
Using a boolean flag: (and fixing your code)
function checkparent(event) {
if (ajaxRequestOn) return;
if (event.target.className == "checkparent") {
ajaxRequestOn = true;
//call ajax functions
$.ajax( /* ...*/ ).always(function () {
ajaxRequestOn = false;
});
} else {
//call local functions
}
}
I think following example might help you.
callbacks = [$.Deferred(), $.Deferred()];
obj1.on('click', callbacks[0].resolve);
obj2.on('click', callbacks[1].resolve);
$.when(callbacks).done(function() { console.log('After to events done'); });
Here I am creating two deferred object.
And each event resolving a deferred object.
when these all deferred object will be resolved next function you can write inside .done()
I think element.type will help you,
HTML
<input type="text" id="tipo-imovel" />
Script
$("#tipo-imovel").on("click change", function(event){
alert(event.type + " is fired");
});
This code will alert which event has been triggered
I'd suggest you to look at this possible events
Please let me know if it helped you
This might help: jQuery queues. Please go on below for the relevant quote:
How can jQuery queues be used here
Working Example
This is an amazing resource on using queues for custom ajax calls. I know the SO preference for archiving linked content, but I can't really copy code here, so I've also made a small fiddle showing custom queues - here
The example uses a text-color change, but that can easily be any AJAX call. The setTimeout has an asynch callback similar to many AJAX calls, this fiddle should be a useful template...
Theory
$('#elementId').click(function (e) {
var $element = $(e.currenttarget);
$element.queue('myqueue', function () {
var $el = $(this);
//Do stuff on $el
//Remove this event from the queue and process next...
$el.dequeue();
});
});
Breaking this down:
Listen to the click event
Get the specific element clicked
Queue a function on the 'myqueue' of this element
The function to be queued may need a reference to this element - luckily jQuery calls it with the required element as the 'this' pointer.
If you desire a gap between two events, you could even put the dequeue inside a timeout like window.setTimeout(500, function () { $this.dequeue(); }); , which sets a 500ms interval before the next event...
jQuery Queue Docs
This feature is similar to providing a callback function with an
animation method, but does not require the callback to be given at the
time the animation is performed.
$( "#foo" ).slideUp(); $( "#foo" ).queue(function() {
alert( "Animation complete." );
$( this ).dequeue();
});
This is equivalent to:
$( "#foo" ).slideUp(function() {
alert( "Animation complete."
); });
Note that when adding a function with .queue(), we should
ensure that .dequeue() is eventually called so that the next function
in line executes.
Update The answer has been modified to include a working fiddle and some explanation as well.

Stuck in infinite loop while trying to intercept form submission

I am writing Javascript/JQuery code, where I want to intercept the form submission before submitting it because I need to check if the fields are valid.
So I block the default event from happening, check what I want to, then fire the event again if everything is ok. Problem is, this triggers the exact same function and I get stuck in an infinite loop.
Is there a way around this? I can think of work arounds, but they are, after all, work arounds and not the most elegant of solutions.
Here is my code:
$("#register_form").submit(function(event) {
event.preventDefault();
console.log('form submit attempt');
checkUsername();
$("#register_form").submit();
});
In order to be able to stop the form submitting if there are errors, you need to return false from the function. You'll need to make sure that the checkUsername() function returns bool.
Try this...
$("#register_form").submit(function(event) {
if(checkUsername())
return true;
return false;
});
Or even better...
$("#register_form").submit(function(event) {
return checkUsername();
});

JQuery do click events stack

I have the following code;
$("#myID").click(function () {
//do something
})
At some point, a user action on another part of the webpage needs to change the action that occurs on the click e.g.
$("#myID").click(function () {
//do something different
})
My question is, what's the correct/most efficient way of doing this? Currently I'm just implementing the second chunk of code above, but will this cause some odd behaviour? i.e. will there now be two different actions performed on click? Or does the second block of code override the first.
They will both execute so no, the second call does not overwrite the first.
Basic jsFiddle example
And as pimvdb notes, they will be executed in the order they were bound.
You can always unbind the click function first: http://api.jquery.com/unbind/
Right, they "stack". I.e. $("#myID") will maintain a list of event handlers, and execute both on click.
If you no longer want the original handler, you need to unbind it, using $("#myID").off('click') or if you're using an old version of jquery, $("#myID").unbind('click')`. http://api.jquery.com/unbind/
In your code, both clicks will be executed.
Try to unbind click event before
$("#myID").unbind("click")
http://api.jquery.com/unbind/
You can add a global variable isAnotherEvent = false and then check on click event which part of code you need to execute, to execute another part simply make isAnotherEvent = true
var isAnotherEvent = false;
$("#myID").click(function () {
if(!isAnotjerEvent){
//do something
} else {
//do something else
}
})
$("#btnChangeEvent").click(function(){
isAnotherEvent = true;
}

Categories