Thursday, October 9, 2014

MakerSquare Day 31: A Million Little Tiny Tricks: Trick one: Delegation (7/3)

Today was our last day of our current project, a single-page application that gave the reader a quiz. Simple enough to do (that is, not at all simple when we started), but then we had several extensions and expansions, like: allowing the viewer to create their own quiz. To do so, we learned all about localStorage, which is where we were storing information about the quiz.

Which brings me to something interesting that we discovered as a class (i.e., something the instructor wasn't quite clear on), which is that you can iterate over localStorage as if it were an array-like structure.

Which brings me to the real topic of this blog-post: there are a lot of high-level topics and concepts in learning programming, everything from abstract patterns (like MVC) to language foundations (objects, type-sensitivity, etc.).

But there's also a whole range of tiny details and little tricks that you pick up along the way, that even really smart and experienced instructors might not know. And I'd like to share some of them, as I pick them up.

Yes, finally, after 28 days, I have an idea for an on-going blog feature!

Today's trick isn't really a trick: it's a life-saving idea about JavaScript and event listeners. Beginning developers (cough, cough) often have a problem where they/we create an HTML button and add a JavaScript listener to the button--only that button is added after the event listener and so the event listener can't find the button.

So there's a nice jQuery fix where you set a listener to load after the page loads:
$(document).on('ready', function() {
...your listeners here...
 But you can also delegate the event listener to the document, like so:
$(document).on(...what event you want to listen to, ...what you want to trigger the event... , function( event ) {...}
That way, the event listener is delegated to the document, which will hand it off to whatever you want to trigger the event, and it will work whenever that event-triggering object is added to the document.

No comments:

Post a Comment