An array defines these elements:
var equipment = new Array( "bakeware", "cookware", "kitchenware", "utensils" );
A function exists that associates these equipment types with editable fields:
function register_equipment( equipment ) {
$('#recipe-equipment-' + equipment).append(
'<span class="edit-recipe-equipment"></span><br />' );
$('.edit-recipe-equipment').editable( 'php/save.php', {
onblur : 'submit',
style : 'display: inline',
maxlength: 15,
size : 10
});
return true;
}
This allows users to click on the field and edit its value. The input field disappears when the user finishes editing.
The following code is duplicated four times (once per equipment item):
$('#equipment-new-bakeware').click( function() {
return register_equipment( 'bakeware' );
});
This works, but it is not ideal.
How would you write the code such that there is no duplication?
The following does not work, but shows the intent to remove the duplication:
for( var i = 0; i < equipment.length; i++ ) {
$('#equipment-new-' + equipment[i]).click( function() {
return register_equipment( equipment[i] );
});
}
Thank you!
Quick answer is to create another scope to capture the correct value. Bit long winded, but this is the idea.
function createOnClick (i) {
// i will be captured in this function and used below
return function () {
register_equipment( equipment[i] );
};
}
for( var i = 0; i < equipment.length; i++ ) {
$('#equipment-new-' + equipment[i]).click(createOnClick(i));
}