Send data along with event

6

As I venture through jQuery some doubts and problems arise in the middle of the path, one of them is: Is it possible to send a data through an event triggered by another event? Something like this:

jQuery

$(".seletor1").on("click", function(){
    $(".seletor2").trigger("click", dados);
});
//
$(".seletor2").on("click", function(dados){
    alert(dados);
});
    
asked by anonymous 05.07.2014 / 07:48

1 answer

6

Yes you can. Example: link

$(".seletor1").on("click", function(){
    console.log('Clicado!');
    $(".seletor2").trigger("click", {animal: 'gato'});
});
//
$(".seletor2").on("click", function(evento, animais){
    alert(evento.type);
    alert(animais.animal);
});

Looking at the jQuery documentation the expected syntax is:

  

.trigger (typeEvent [ ParametersExtra])

     

Type Type: String
Description : A string containing the event name . For example 'click' or 'submit'

     

ParametersExtra Type: Array or Object Description : Additional parameters to pass with the event.

If you want to mix this click handler with a true click you can create a if to check if the extra object has been passed. Suggestion:

$(".seletor2").on("click", function (evento, animais) {

    if (!animais) {
        alert("Clicou no seletor2");
        return false;
    }

    switch (animais.animal) {
        case 'gato':
            alert("Clicou no seletor1");
            break;
        case 'cao':
            alert("Clicou no seletor1");
            break;
        case 'elefante':
            alert("Clicou no seletor1");
            break;
    }
});
    
05.07.2014 / 07:58