views:

54

answers:

4

So I have a grid on a page that displays tablular data, with a checkbox by each row.

So in this situation, when a checkbox is clicked, allot of things will react on the page potentially.

Also, if a button is clicked, again allot of things will potentially react on the page.

So say if someone checks a checkbox, the row should be highlighted, there is a toolbar that will show/hide buttons, etc.

If someone were to click on the toolbar directly, again things similiar to when the checkbox was clicked will react.

So what I want to do is this, whenever a checkbox is clicked, or whenever a toolbar button is clicked, I want to 'announce' to anyone who is listening that this event occurred.

I can then, based on the source of the event, react in a similiar or different manner.

how to best go about designing things like this?

A: 

You could try YUI Custom Events. This allow you to fire off your own "event" which listeners can hear.

Rob
I believe jquery also does custom events.
Justin Johnson
+2  A: 

I think you want to look into using the Observer Pattern. Basically, interested parties subscribe or listen for an event on a publisher, and when the event occurs, the source notifies all the listeners of it.

SB
+1 for promoting a pattern. Although in JQuery it's kinda tricky to use Classes. That's why i like Mootools =)
pleasedontbelong
A: 

I like how it works with jquery, since you can bind an event to many elements at once.

$("input[type=checkbox]").click(function(e){
    alert(e.currentTarget.id);    
    });

This code would make all checkboxes alert their name. Of course, by using css classes, you could bind a subset of all checkboxes to create an action.

$("input[type=checkbox].cssClass").click(function(e){    
    someOtherFunction(e.currentTarget);
    });
Aspelund
+1  A: 

two things come to mind:
1. event delegation (you don't want to bind to each input on the grid) look at this link to a great way of doing this while also maintaining a clean code: by ben nadel
2. using custom events, or even better - use this pub/sub plugin

i have a large grid like this in my app that evolved over time, and manually binding to each input + responding in different ways caused the code to be a "bit" ugly,
It's great that you now where you are going and prepare up front

Avi Pinto