Create custom .ON events in jQuery

1

I hope you can help me, because I want to know this and I have not found anything useful in the searches. Basically what I want is to do as a listener if that is how it is said, waiting for another function to react (or make a callback, I think), and when you receive information, that is activated. I have a socket, which receives information, and I want it to react when I notify the on chat event and send it parameters as well. I do not know if I explain myself well, but I'll leave a few lines of code as an example:

connection.on("Chat"){
alert(evento.parámetro)
}
    
asked by Esteban Fernández 14.12.2018 в 18:17
source

1 answer

2

I think what you need is to use the function trigger , this function executes all the controllers and behaviors attached to the matching elements for the given event type, you can add an example:

$("#myButton").on("myCustomFunction", function(e, myStr){
        alert("Prueba "+ myStr);
    });
 
    $("#myButton").click(function(){
    
    var myStr = "de mensaje";
        $("#myButton").trigger("myCustomFunction", [myStr]);    
    });
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label>Click sobre el Botón!</label>
<input type="button" id="myButton" value="Click Me!">

I also give you another example a little more elaborated that I found in case it benefits you:

$("#example-section26 div").bind("HighlightEvent", function(e, color, colorTitle){
        $(this).html("Custom event triggered - " + colorTitle);
        $(this).css("background-color", color);
    });
 
    $("#btn261").click(function(){
        $("#example-section26 div").trigger("HighlightEvent", ["orange", "Color Orange"]);    
    });
 
    $("#btn262").click(function(){
        $("#example-section26 div").trigger("HighlightEvent", ["green", "Color Green"]);    
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a name="#custom-event-example"></a>
<div id="example-section26">    
    <div>Build your own event</div>
    <input id="btn261" type="button" value="Trigger custom event(Orange background)">
    <input id="btn262" type="button" value="Trigger custom event(Green background)">
</div>

Annex the documentation so that you consult it in case you have doubts about it: link . I hope it is helpful. Greetings.

    
answered by 14.12.2018 / 20:11
source