javascript - Which Is A Better Way Of Writing Content Population? -


let's have 10 divs unique ids. when click on element within each wish show overlay div , populate content within based in id of original div.

is better do:

$('#inventory > div').find('i.icon-plus').on('click', function(){     $('#add-item').slidedown(100);     if ( $(this).parent('div').attr('id') == '#id1' ) {         // load unique template         // or         // create form content here     }     else if ( $(this).parent('div').attr('id') == '#id2' ) {         // load other unique template         // or         // create other form content here     }      ...      else if ( $(this).parent('div').attr('id') == '#id10' ) {         // load other unique template         // or         // create other form content here     } }); 

or:

$('#inventory > div#id1').find('i.icon-plus').on('click', function(){     $('#add-item').slidedown(100);     // load unique template     // or     // create form content here }); $('#inventory > div#id2').find('i.icon-plus').on('click', function(){     $('#add-item').slidedown(100);     // load unique template     // or     // create form content here });  ...  $('#inventory > div#id10').find('i.icon-plus').on('click', function(){     $('#add-item').slidedown(100);     // load other unique template     // or     // create other form content here }); 

?

basically i'm asking is: better have 1 event handler ton of if/else statements or ton of event handlers no if/else statements, or not matter?

i suggest use on delegate event handlers parent, avoiding jquery having attach handlers each i.icon-plus.

then use map of handlers ids keys functions run corresponding code. way, won't appending lot of if statements.

each "case" may contain code repeating which, if knew, further optimized. since don't know each block of mapped functions do, here's generic code should serve same purpose:

//add handles here, id key ,  //corresponding function supposed var handles = {   '#id1' : function(){/*do something*/},   '#id2' : function(){/*do something*/},   ... }  //let's cache 1 var additem = $('#add-item');  $('#inventory > div').on('click','i.icon-plus', function(e){      //get corresponding handler     var handler = handles[$(this).parent('div').attr('id')];      //return if handler isn't defined id     if(!handler) return;      //otherwise, execute. context , arguments passed on     additem.slidedown(100);     handler.apply(this,arguments); }); 

this can further optimized if div referenced #inventory > div, our delegate target, same div $(this).parent('div'). if so, can replaced reduce function calls:

$(this).parent('div').attr('id')  //can replaced  $(e.delegatetarget).attr('id') 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -