Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created September 15, 2016 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoward/5c6d4dfe72330ac98e6efb2f4073f002 to your computer and use it in GitHub Desktop.
Save ahoward/5c6d4dfe72330ac98e6efb2f4073f002 to your computer and use it in GitHub Desktop.
<!--
using ids is effectively just like using a GOTO statement in code - it pins
logic to jump to a pre-labeled and identified spot by unique label/id. this
lets you avoid needing to make a good design.
-->
<div id='book'> </div>
<script>
$.ajax(book_url, function(data){
$('#book').html(data.title);
// GOTO #book, insert title
});
</script>
<!--
using a class drives you towards designing relative, vs absolute, components,
and this trickles down by making code less fragile and far more re-usable
set based logic, like jquery, is powerful and reusable - and it doesn't make
you re-build entire swaths of logic and html just because a feature makes
something that was unique on page, non-unique
also, by working in sets/classes you end up building js that takes advantage
of local vars vs leaning on closure based refs to unique (effectively global)
objects that all your logic slaps around accessing.
tl;dr; classes + functions : enacapsulated and resuable. ids + closures : leaky and non-reusable.
-->
<div class='book' data-book-id='1'></div>
<div class='book' data-book-id='2'></div>
<script>
$('.book').each(function(){
var $book = $(this);
var url = '//books/' + $book.data('book-id') + '.json';
$.ajax(url, function(data){
$book.html(data.title);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment