Category Archives: javascript

Raphael.js event handlers sometimes require closures

I’m playing around with raphael. In the code below, I use a few loops to make a grid of rectangles. I want each rectangle turn from white to gray when clicked. This is a little tricky in raphael, because you can’t use this or evt.target to get a reference to what got clicked on.


var main = function () {
    var paper = Raphael("grid", 320, 200);
    for (var rownum=0; rownum<3; rownum+=1) {
        for (var colnum=0; colnum<3; colnum+=1) {
            var r = paper.rect(10+colnum*50, 10+rownum*50, 50, 50);
            r.attr({stroke:"gray", fill:"white"});

            r.node.onclick = function () {
                var this_rect = r;
                return function () {
                    this_rect.attr({fill:"gray"});
                }
            }();
        }
    }
};
window.onload = main;

Remember that your typical boring onclick assignments usually look like this:


r.node.onclick = function () {
    alert("your mom");
};

I don’t call the function. I just define it.

Study the r.node.onclick assignment in the main code again, and make sure to notice that the r.node.onclick attribute is assigned to the result of the function defined.

That’s the first big difference. Now you have to figure what the heck is returned by this function. The answer is. . . another function. That other function is what gets linked up to be fired when a click event happens.

Closures are tricky at first, but they’re really useful for situations like this, when you need to pass along references with the functions to operate on them.

Approaching jQuery popup callback hell

I wrote this post on the jQuery mailing list and nobody replied, so I’m pasting it here. I could really use some advice.

I’m using a modal dialogs and I love them, but I haven’t found a really elegant way to handle actions in the dialog window that require changes to the parent page.

Here’s an example. I have a monthly calendar page that lists employee names on the days they are supposed to work. Clicking on an employee name opens a “shift detail” page in a modal dialog.

That shift detail page has more information like the specific tasks planned for the day, the start time and stop time of the shift, etc. From this shift detail screen, I can remove this particular employee from the schedule by submitting an AJAX POST from this popup.

After I remove the employee, I need to update both the popup window and the original page that hosted the link to the popup window. Right now I do this by adding a callback that fires when the AJAX POST succeeds. That callback then updates both pages. The callback is named “after_remove_employee”.

This system gets really nasty when I use the “shift detail” popup on different screens. For example, in addition to the monthly view, I also have a weekly view with more information. So after an employee is removed from the schedule on the weekly view, I need to do some different things in the callback.

Right now, the way I handle this is that I define the same callback twice. I define “var after_remove_employee = function (data) {…} on the weekly view to do what it needs there, and then I define it differently on the monthly view.

I’ve simplified the problem to help explain it. In reality, I have lots of different popups on lots of different pages, and in each popup, there are many different possible actions.

I’m sure I’m not the only one that’s been in this scenario. What is an elegant solution?

I’m thinking about using custom events. So, the callback after a successful AJAX POST would just fire an “employee removed” event, and everybody subscribed would get a reference to the event object and do whatever they want.

However, I’ve never used JS events before, and I don’t know if this is even possible.

Please, any feedback is welcome.

jQuery for the win

I needed to toggle some text between “show help” and “hide help”.

First, I wrote this and thought I was good:

<style type="text/css">
span.hide { display:none }
</style>
<script type="text/javascript">
$(document).ready(function () {
    $("a.showhide").click(function (event) {
        $("span.show").toggle();
        $("span.hide").toggle();
        return false;
    })
});
</script>
<a class="showhide"><span class="show">Show Help</span><span class="hide">Hide Help</span></a>

That flips the text from “Show Help” to “Hide Help”. But the code can be made even shorter by calling toggle on both spans at once:

<script type="text/javascript">
$(document).ready(function () {
    $("a.showhide").click(function (event) {
        $("a.showhide span").toggle();
        return false;
    })
});
</script>

I heart jQuery.

I need the straight dope on jQuery

I really like how tiny the library is. It is nice that I can use selectors to find nodes; for example, $(“li a”) will find all the anchors inside list elements. Furthermore, it seems really well documented. There’s not just one, but several real books all about jQuery available on amazon.

So, what am I overlooking? What’s the terrible secret of jQuery?

How I spent Saturday night

My wife keeps winning when we play scrabulous. So I wrote some performance-enhancing javascript here to close the gap.

The first time the page loads, you have to download the whole 1.4 mb word dictionary. Then your browser will cache that file locally, so future look-ups are really quick.

There’s at least one bug so far. When you submit your list of tiles like ABCDEFG and your pattern B..Y.. I make a regular expression object where I replace each dot with [ABCDEFG]. So that means I’m not keeping track of how many of each tile you have. If the BGGYGG were a real word, then my function would suggest it, even though this is clearly impossible.

Along with fixing that bug, I want to make a few improvements:

  • Figure out how to make this into a firefox extension.
  • Display the score next to each word suggestion.