Organizing a jQuery Event Handler

I am looking for a recommendation on the best way to organize my code. I have many jQuery event handlers that are used for:

  • drop down menus, tabs, etc.
  • form validation
  • $. ajax get requests for dynamic form<options>
  • $. ajax messages to submit the form.

An MVC structure like backbonejs seems redundant, but my current code is not supported and will continue to deteriorate unless I give it some kind of structure.

$('#detailsform').find('.field').on('click','.save',function(){
    var input = $(this).siblings().find('input');
    input.attr('type','hidden');
    $(this).siblings().find('p').text(input.val());
    $(this).text('Change').addClass('change').removeClass('save');
    url = null; //query str

    $.ajax({
      type: "POST",
      url: url,
      data: data,
      success: success,
      dataType: dataType
    });
});
//next event listener 
//next event listener 
//next event listener 
//next event listener 

which is one of many event listeners. Any suggestions on organizing this?

+4
source share
1 answer

. eventHandlers , . .

(function() {
    var Site = {
        init: function() {
            this.bindEventHandlers();
        },
        bindEventHandlers: function() {
            for (var i=0; i<this.eventHandlers.length; i++) {
                this.bindEvent(this.eventHandlers[i]);
            }
        },
        bindEvent: function(e) {
            e.$el.on(e.event, e.handler);
            console.log('Bound ' + e.event + ' handler for', e.$el);
        },
        eventHandlers: [
            {
                $el: $('#element1'),
                event: "click",
                handler: function() { console.log('Clicked',$(this)) }
            },
            {
                $el: $('#element2'),
                event: "click",
                handler: function() { console.log('Clicked',$(this)) }
            }
        ]
    };

    Site.init();
})();

: http://jsfiddle.net/chrispickford/LQr2B/

+5

All Articles