Skip to content

Instantly share code, notes, and snippets.

@brunops
Created May 16, 2016 04:14
Show Gist options
  • Save brunops/acade902983242d39ffa44dff34b4a00 to your computer and use it in GitHub Desktop.
Save brunops/acade902983242d39ffa44dff34b4a00 to your computer and use it in GitHub Desktop.
avoid anon callbacks
// don't do this
$(document).ready(function () {
$.get('/foo', function (response) {
var list = $('<ul />')
response.list.forEach(function (item) {
list.append($('<li />').text(item))
})
$('#content').append(list)
})
})
// SEPARATE YOUR CODE INSTEAD
// do this:
function getList(list) {
var listEl = $('<ul />')
list.forEach(function (item) {
listEl.append($('<li />').text(item))
})
return listEl
}
function render(element) {
$('#content').html(element)
}
function ajaxSuccess(response) {
var list = getList(response.list)
render(list)
}
$(document).ready(function () {
$.get('/foo', ajaxSuccess)
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="content"></div>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment