Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event handler organisation

I am looking for a recommendation on the best way to organised my code. I have a lot of jQuery event handle which are used for:

  • dropdown menus, tabs etc
  • form validation
  • $.ajax get requests for dynamic form <options>'s
  • $.ajax post requests for form submitting.

An MVC framework like backbonejs seems like overkill but my current code isn't maintainable and will continue to get worse 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 

that is one of many event listeners. Any suggestions on how to organise this?

like image 718
TarranJones Avatar asked Mar 22 '23 00:03

TarranJones


1 Answers

I would use the following structure. Simply add more objects in the eventHandlers array for each element you need. This could even be done programatically.

(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();
})();

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

like image 110
Chris Pickford Avatar answered Apr 02 '23 05:04

Chris Pickford