In a previous post I gave a basic example on how to create a simple callback function: http://webconfiguration.blogspot.co.uk/2012/10/javascript-creating-method-with.html
In this post I will demonstrate how to combine this simple callback example with a more complex function (i will use the sorting method i posted previously: http://webconfiguration.blogspot.co.uk/2012/10/javascript-sort-select-and-lists.html )
Step 1
Calling the method with the selectbox as the callback:
sortList(‘select#country’, function(obj){
obj.selectbox();
});
Step 2
The sorting method running the function passed as a paramter, ie the callback:
/*ordering lists*/
sortList: function(selector, callback) {
/*varring up the object*/
var selector_object = $(”+selector+”);
/*hide the select whilst shuffling*/
selector_object.hide();
/*determin element type of*/
switch ( selector_object.prop(‘tagName’)){
case ‘UL’ : var childType = ‘li’;
break;
case ‘SELECT’ : var childType = ‘option’;
break;
}/*start the arrays*/
var listElement = new Array();/*populate array of elements*/ $(”+selector+’ > ‘+childType+”).each(function(){
var element = $(this).clone().wrap(‘‘).parent().html();
listElement.push({key: element, value: $(this).html() });
})/*sort the object*/
listElement.sort(function(a, b){
if(a.value > b.value){
return 1;
}
else if(a.value < b.value){
return -1;
}
return 0;
});/*empty the repopulate sorted*/
selector_object.empty();
$.each(listElement, function(a,b) {
selector_object.append(b.key);
});
/*hide the select whilst shuffling*/
selector_object.show();
/*Check the callback param exists and is a function then run it*/
if (callback && typeof(callback) === “function”) {
callback(selector_object);
}
}