Monthly Archives: September 2012

If you’ve used jquery, you’ll be used to attaching click events etc to items:

// for <a class="delete" href="{url}">, get user confirmation
// before navigating off to {url}

$('a.delete').click(function () {
    return confirm('Really?');

Sometimes though, the items you want to attach behaviours to don’t exist yet (e.g. because they’re created and destroyed dynamically in response to UI interaction).

You could attach the behaviour at the point you create the new element, but if you’re doing that in several places, you’ll have the same code in various places. Plus, your implementation of the behaviour for one kind of element will be buried inside the implementation of the behaviour of some other kind of element (or refactored into a function in some more public scope than it ought to be).

It turns out that jquery has a method .on() which allows you to attach event handlers to elements that may or may not yet exist:

$('body').on('click', 'a.delete', function () {    return confirm('Really?');});

The documentation explains how this works (attaching the handler to some parent element — the body element in the above example — and using browser event bubbling to catch events originating on the selected children).

It’s quite nice, you end up with quite a clean pattern whereby you create elements with a CSS class for which you have previously defined the behaviour using .on().

I was processing a UTF-8 dataset where the performance copyright symbol (Unicode code point 0x2117) had been entered as ASCII “(P)”. I wanted to replace this sequence with the actual symbol, but I didn’t know how to create an arbitrary UTF-8 character. After a bit of googling (more than 5 mins, otherwise I wouldn’t be posting!) here’s the answer:

txt = re.sub(r'[(]P[)]', unichr(0x2117).encode('utf-8'), txt)
%d bloggers like this: