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:
<options>
's 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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With