开发者

best practices for designing a page with lots of events

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 similar to when the checkbox was cl开发者_如何转开发icked 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 similar or different manner.

how to best go about designing things like this?


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.


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


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


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);
    });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜