views:

32

answers:

3

I'm doing this over and over, and I'm not sure if it is the best way to do so in JavaScript/jQuery. I have a function that acts as an event handler, but also I need to call it on page initialization. Thus I have been using the following code:

<script type="text/javascript">
    $(function() {
        function doToggle() {
            $("#toggle-fields").toggle(!$('#checkToggle').is(':checked'));
        }
        doToggle();

        $('#checkToggle').click(doToggle);
    });
</script>

How do you tackle this repetitious situation? Are there any best practices that you can point me toward?

+2  A: 

Your code will not work because this will be window in the first call.

Change it to

doToggle.call(document.getElementByID('checkToggle')); 
SLaks
+2  A: 

One way to do it is :)

$('#checkToggle').click(doToggle).click();
Anurag
Note that this will also trigger other handlers.
SLaks
@SLaks - that's true, but I'm thinking of this from a UI perspective. Put the application in an initial state that it would be in *if* the element was clicked (which means all attached handlers will indeed run).
Anurag
Good idea. However, if he has non-idempotent handlers, he should be aware of that.
SLaks
is binding and triggering `click.toggle` not a good idea?
Reigel
@Reigel - Namespacing is definitely not a bad idea at all. In fact, it is a very good idea.
Anurag
+2  A: 

like this...

$(function() {
    $('#checkToggle').bind('click.toggle',function(){
        $("#toggle-fields").toggle(!this.checked);
    }).trigger('click.toggle');
});
Reigel