Skip to content

Instantly share code, notes, and snippets.

@ppazos
Last active March 2, 2018 17:18
Show Gist options
  • Save ppazos/620c4fa8229006948c4a401946726651 to your computer and use it in GitHub Desktop.
Save ppazos/620c4fa8229006948c4a401946726651 to your computer and use it in GitHub Desktop.
Pattern to separate ajax calls from the response rendering logic using callbacks
var render = function(param1, param2, param3, model)
{
// process model and generate dom to display it
// sample code to display a select with key/value from model
_select = document.getElementById(param1);
for (key in model)
{
option = document.createElement("option");
option.value = key;
option.text = model[key];
_select.add(option);
}
// binded params can be ids of dom elements where the mode data should be displayed
// if the generated dom also needs some js even listeners, we can pass an extra callback
// "register_liteners" to register those event listeners, and use the params to set the
// ids of the dom elements
};
var do_ajax = function(callback) {
$.ajax({
url: 'an_url',
data: {}, // add request params as key: value
dataType: 'json', // change to correct datatype
success: function(model, textStatus)
{
callback(model); // does render of model
},
error: function(xhr, textStatus, errorThrown)
{
console.log(xhr, textStatus, errorThrown);
}
});
};
// call
// bind params for render callback
var render_callback = render.bind(null, param1_value, param2_value, param3_value);
do_ajax(render_callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment