I have Peter Bailey's second answer, in which it is best to keep your MV and C separate. I found a better style for GUI widgets to create a function that initializes the widget (by creating HTML, adding a style, or adding animation events) and then adding custom event handlers for different places where it is used.
Custom events are key to multiple widgets. This makes the code less fragile for DOM changes in your GUI widgets and makes your code more readable.
For example, let's say you have a custom button that dynamically creates an HTML structure as follows:
<div class="MyButton"><div class="button-helpful-wrapper"><img src="/blah.png"/></div></div>
Say your initialization code adds some attenuation or something else using click events. It does not matter.
An interesting bit is when you want to use this button; to which div do you attach the 'click' event to? instead of knowing the structure of your GUI widget, it would be better to just create a new event type for the widget. For example:
$('#MyButton_Instance1').bind('myclick', function () {...} );
And completely agnostic about the structure of the widget.
To make this work, all you have to do is add some bundles / triggers that proxy the actual event for your custom event. The best place to do this can be found in the widget initialization code:
$('.MyButton').myButton();
Where
myButton = function () { $(this).find('.button-helpful-wrapper').bind('click', function (event) { $(this).trigger('myclick', event); }); }
This makes your widgets very reusable, because you are not attached to specific events of DOM objects, but rather to the general event of the widget. Give it a try.
brendan
source share