1

I'm an intermediate JS programmer and it's a world of difference from PHP (esp. when I'm not an OOP programmer even in PHP).

I am interested in defining my own events in jQuery as a possible simplification of my programming, and I'll use a simple example:

often you have rows of records in a table. user wants to make a row inactive. System is set so that when this happens the row fades out and disappears. Let's suppose there could be 3 ways to do this:

  1. hit an inactive icon
  2. with the row highlighted hit i or
  3. right click and select inactive from a context menu.

what I'd like to do is something like:

$('.datarow').on('rowinactive',function(){ /* etc */ });

any of the three actions above would set $('#row12345') as .inactive, and the event handler would take it from there. I see it as you have somewhat of a separation between the state and the action(s) related to the state.

I hope this is a simple example to start. Can anyone offer some example code for this?

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Samuel Fullman
  • 1,262
  • 1
  • 15
  • 20

4 Answers4

5

You can define pretty much any event you'd like, but such events would have to be triggered somewhow.

$('.datarow').on('rowinactive',function(e, elem){
    alert(elem.id + ' is inactive');
});

$('table tr').on('click', function() {
    $(this).highlight();
    $('.datarow').trigger('rowinactive', this); // passes the element
});

you can also pass any parameter to the triggered function.

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1
$(function(){
    $("input").on('customEvent',function(){ //define a custom event listener
        $("p").text("hello");
    });
    $("input").trigger('customEvent'); //call the event listener attached to obj. with name 'customEvent'
});

I've made an example which you can play with here. You could exapnd this idea to apply a a custom event to multiple objects collected by a specifict $(...). Then as each object may have a different interaction with the user, you can invoke the action appropriatley, i.e for an input you might trigger customEvent on click, while another when it's inactive etc...

HennyH
  • 7,794
  • 2
  • 29
  • 39
1

Without the markup is a bit difficult to help, so i'll make an example using only the hypothetical "inactivate" icon.

$('.inactive-icon').on('click',function(){
    var $row = $(this).closest('.datarow');
    $row.fadeOut(500,function(){
        $row.trigger('inactive'); // ---> it's that simple!
    });
});

$('.datarow').on('inactive',function(){ /* etc */ });
Giona
  • 20,734
  • 4
  • 56
  • 68
0

Check this Fiddle.

$("tr").bind("fadeOut", function(){ /* code */ });
$("tr").trigger("fadeOut");
Jorge Loureiro
  • 458
  • 3
  • 11