A template for connecting events with jQuery

Please see the code at the end to see the method I used to hook up events in my jQuery code. I prefer to use bind and as you can also see, I don't like using anonymous functions in event handlers.

I use named functions for the following two reasons:

  • readability
  • Multiple calls to my WireUpGlobalCommandClickEvents won't add multiple event handlers to my link click.

This has a side effect: I need to pass data to OnAddNewSnippetClick using the bind function, as in OnAddNewSnippetClick this now refers to the element that triggered the event.

I've always viewed JavaScript as a second-class citizen, and as you can see, I'm trying to enforce the conventions I use in my ASP.NET MVC application into my JavaScript here. Is my paranoia about multiple event handlers added out of place? Is there a better pattern for connecting event handlers with jQuery?

SettingsController.prototype = {

    OnAddNewSnippetClick: function(event) {
        event.data.SettingsController.SettingsAjaxHelper.AddNewSnippet(event.data.Parameter, event.data.SettingsController);
    },

    WireUpGlobalCommandClickEvents: function(parameter) {
        $('#addSnippetLink').bind("click", { SettingsController: this, Parameter: parameter }, this.OnAddNewSnippetClick);
    }
};

      

+1


a source to share


1 answer


If you are really paranoid about binding multiple events, you can use live, which automatically binds events based on a selector.

 $(".stuff").live('click',function(){});

      

or

$("#element").one('click',function(){});

      



or

$("#element").unbind('click').bind('click',function(){});

      

But yes, it looks like you are trying to do MVC in javascript which will probably overdo it

http://docs.jquery.com/Events/live#typefn

+2


a source