views:

195

answers:

1

Please look at the code at the end to see the method I've been using to wire up events in my jQuery code. I prefer using bind and as you can also see I don't like using Anonymous functions in my event handlers.

I'm using named functions because of the following two reasons:

  1. Readability
  2. Multiple calls to my WireUpGlobalCommandClickEvents will not add multiple event handlers to the click of my link.

This has a side effect - I need to pass in data to the OnAddNewSnippetClick using bind's functionality, since in OnAddNewSnippetClick, this now refers to the element that caused the event to fire.

I've always treated JavaScript as a second-class citizen and as you can see I'm trying to force the conventions I use in my ASP.NET MVC application onto my JavaScript here as well. Is my paranoia about multiple event handlers being added misplaced? Is there a better pattern to wire up event handlers using 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: 

if you're really paranoid about multiple events being bound, you can use live, which auto wires up events based on the selector.

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

or

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

or

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

But yes, looks like you're trying to do MVC in javascript which is probably overkill

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

Chad Grant