rc3.org

Strong opinions, weakly held

Month: March 2008 (page 3 of 4)

jQuery evangelism

For the past few weeks, I’ve been completely obsessed with jQuery, one of the many fine JavaScript UI libraries that are competing for your attention these days. I can’t really tell you whether jQuery is better than any of the other libraries, but I can say that it’s infinitely better than writing your own JavaScript by hand, and that it’s very approachable. You can start doing really powerful things with jQuery with a very small time investment, especially if you already know a little JavaScript and you understand CSS selectors.

Rather than provide a full primer on how jQuery works, I thought I’d provide an example of the kinds of thing jQuery makes easier. Here’s some real JavaScript code:

$(document).ready(function(event) {
    $("#sameAsPhysical").change(function(event) {
        if (event.target.checked) {
            $("#physical input").each(function() {
                $("#billing input[name='" + $(this).attr("name").replace(/physical/, "billing") + "']").val($(this).val());
            });
        }
    });
});

Here’s how the code works. I have a form that has two fieldset elements. One contains the fields for the physical address for a business, the other contains the fields for the billing address. Because the fields are in the same form, they need different names, so all of the physical address fields begin with physical and all the fields associated with the billing address start with billing.

The first thing I do in this code is bind a handler to the onChange event for a checkbox with the ID sameAsPhysical. Like every other JavaScript library, jQuery provides a facility for binding events to elements at page load time, allowing you to follow the tenets of unobtrusive JavaScript. In this case, I bind an anonymous function to $(document).ready(), which fires when all of the page content has loaded. I do all of my other event binding inside that anonymous function.

My goal here is to bind a function to the onChange event associated with my checkbox. Here’s where the “query” part of jQuery comes into play. To get a reference to the checkbox, I just use $("#sameAsPhysical"). As you can probably tell, that query selects an element with the ID sameAsPhysical, just like it would in a style sheet.

jQuery makes event binding simple by adding methods to selectors for each of the events that you can associate with them. So to bind a function to the onChange event, you just call change() on the results of your query. If the query returned a list of elements, the same function would be bound to all of the elements in the query results, as you’ll see in a moment.

Inside the event handler function, I need to check to see whether the checkbox (which has the label “Same as physical address”) is checked, and if it is, I copy all of the values from the “physical” fields to the “billing” fields.

jQuery helpfully passes in the event being captured to my function, so to check the state of the checkbox, I use the expression event.target.checked. If the box is checked, I copy the values. Now for the cool part.

First I query for $("#physical input"), which returns a list of all of the input elements inside an element with the ID physical. I call the each method on the results, which calls the function passed to it as an argument on each of the elements returned. Inside the function I’m going to copy the value in the field passed to each‘s callback to the value of the corresponding field in the other fieldset, containing the billing address fields.

Let’s look at this line of code:

$("#billing input[name='" + $(this).attr("name").replace(/physical/, "billing") + "']").val($(this).val());

First I grab a reference to the corresponding billing field for the physical field being processed. (Remember we’re inside a loop that’s iterating over the fields in the physical section of the form.)

jQuery goes beyond CSS selectors and provides some XPath-like features. In this case, I write a jQuery that looks like this #billing input[name='billing_address']. That returns any input fields in the billing section that have a name attribute set to billing_address. jQuery selectors are ridiculously powerful.

To create the billing_address name, I use a JavaScript expression: $(this).attr("name").replace(/physical/, "billing"). The trick here is that $(this) is a reference to the current element being passed into the callback function associated with the each method. So I replace “physical” in the name of that element with “billing” to grab the billing field that corresponds with this.

jQuery adds a convenience method to elements that are form fields, called val(). If you call it without an argument, it returns the value in that form field. If you pass it an argument, it sets the value of the field to the argument. So .val($(this).val()) sets the value of the field I looked up (using the name I constructed) to the value of this, which again is the form field passed in by each.

Needless to say this one line of code accomplishes a whole lot, and it’s par for the course with jQuery. You can get an amazing amount done with only a couple of lines of code. Here’s another much simpler example:

$("p.note").prepend('<span class="red">Note</span>: ');

This is a way to fake the ability to use the :before CSS pseudo-selector and the content property. It finds all of the paragraphs with the class note on the page and prepends my text label before the content in the tag.

These are all things you can do with JavaScript alone or with any of the libraries out there, but what I like about jQuery is that it allows you to accomplish these kinds of things with very little code, using a query language that’s easy for humans to comprehend. It doesn’t matter how powerful a tool is if you don’t actually use it, and I find jQuery to be a tool that’s easy to find ways to use. I highly recommend checking it out.

Against torture

The Washington Monthly devotes its full issue this month to articles arguing for a ban on torture. The Bush administration’s continual demand that we must be allowed to torture prisoners is the greatest blow to US moral standing in my lifetime. Plus, it makes me sick. Here’s how the magazine introduces the issue:

In most issues of the Washington Monthly, we favor articles that we hope will launch a debate. In this issue we seek to end one. The unifying message of the articles that follow is, simply, Stop. In the wake of September 11, the United States became a nation that practiced torture. Astonishingly—despite the repudiation of torture by experts and the revelations of Guantanamo and Abu Ghraib—we remain one. As we go to press, President George W. Bush stands poised to veto a measure that would end all use of torture by the United States. His move, we suspect, will provoke only limited outcry. What once was shocking is now ordinary.

President Bush has since vetoed that bill.

There were also two articles this weekend on the language of torture that are worth reading. Fred Clark muses on how newspapers have stopped using the word torture. William Safire explains the origins of the word waterboarding, which used to be more commonly referred to as “water torture.”

Real estate numbers that astound

Here’s an astounding statistic: 10% of homeowners have no equity at all in their homes. Click on the link to read about some of the implications of that number.

In related news, aggregate home debt exceeds home equity for the first time since 1945.

The aesthetics of politics

Tyler Cowen posts about Hillary Clinton and Barack Obama on the same themes that I was trying to hit last night. His post has the advantage of being both shorter and more erudite. He argues that the differences between the two are aesthetic, which I think is exactly right:

The two candidates represent two diametrically opposed portraits of the relationship between aesthetics and politics. Should we expect beauty, grace and universality, or should we derive our feel-good sentiments about politics from righteousness, confrontation, and sheer dogged persistence and feelings of ultimate desert?

The physics of control

When Apple announced the iPhone, there were no provisions whatsoever for third party applications. If you wanted to use the iPhone, you used Apple’s applications. People (myself included) went nuts over it, and Apple responded by telling developers to write Web apps.

Many people strongly suspected that Apple had plans for more than that from the beginning, but nobody really knew what those plans were or when they would be announced. Last October, Apple promised to announce support iPhone-native applications in February, and yesterday we saw what the landscape for those applications would look like.

In terms of ease of development and ease of deployment, the iPhone looks great. The development tools are free to use, and it only costs $99 to register as an iPhone developer, which enables you to distribute your applications through the store application that will be installed on every iPhone as of June. The catch is that there are a number of restrictions on what developers are allowed to do, and that deployment to the iPhone is tightly controlled by Apple. The only way to get your app onto the phone is with iTunes or the phone’s store application, and you have to pay Apple 30% of your licensing fee for the privilege.

It’s the classic walled garden scenario. Apple’s garden looks very nice, but they are intent on remaining the sole gatekeepers when it comes to controlling the iPhone (and iPod Touch). Clearly Apple still has not surrendered to the idea that iPhone is a general purpose computing device that users can tinker with as they wish.

John Siracusa has some interesting musings on whether this walled garden approach can really work, and on what the implications are for independent developers. As he points out, the trend in the computer industry and the mobile device industry is toward open platforms, and you have to wonder successful Apple can be resisting that trend.

Will Apple’s strategy still work five years from now, if Android takes off among handset providers and independent developers? I doubt that Apple is willing to find out. It’s a lot easier to surrender control than it is to reassert control once surrendered. It seems to me that Apple is being very conservative with the iPhone, but at the same time, that they’re listening to customers and relinquishing control at their own pace. At the same time, they have people doing massive amounts of market research for them by jailbreaking and augmenting their phones. I’m certain that the team working on the iPhone SDK was keeping track of what the pain points were for the people writing unauthorized software when they were designing the SDK.

I think it’s a mistake to assume that the business model for iPhone developers will be the same two years from now as it will be in June when iPhone 2.0 launches, and I think it’s a mistake to assume that the API restrictions imposed on developers then will be the same as they are now, as well. Smart analysts will be trying to figure out why Apple is imposing those restrictions. Once they’ve cracked that case, they’ll probably have a good idea of what has to happen for those restrictions to be lifted.

What Obama may lack

Preface this by noting that I’m no political analyst and some would say that my abilities as an analyst of human nature are lacking as well. In spite of those insufficiencies, I’ve been trying to figure out what’s kept Barack Obama from breaking through with a wider swathe of Democratic voters.

Needless to say, given a formidable, well-funded opponent who started with the support of the party establishment and massive name recognition, he has done remarkably well. In spite of a suboptimal result on Tuesday, he’s still got the inside track on the nomination, and he has raised a ridiculous amount of money so far. The people who support Obama really, really support Obama. He does well among independents, but never seems to be able to get more than half of the self-identified Democrats to support him, and I have a theory of why that’s the case.

What strikes me about Obama is that as a politician, he seems unwilling or even unable to campaign based on negative emotion. I mean something different here than negative campaigning, which is usually defined as trying to drive up the negative impressions voters have of your opponent rather than trying to drive up the positive impressions they have of you.

Obama always wants to appeal to our hope for a better America, and to the idea that if people work together, they can effect change. What he seems to avoid is playing to fear, envy, greed, and the other negative emotions that are the refuge of the demagogue. Every once in awhile he’s willing to tap into indignation, but that’s about as far as he’ll go. The medical insurance flier that his campaign produced that tries to scare people about Hillary’s health care plan is notable mainly for the fact that it’s unusual. Most politicians serve voters a daily diet of this stuff.

The problem for Obama is that these are the kinds of appeals that are most effective with a large number of voters. They want red meat. John Edwards based his campaign on setting working people against corporations and rich people. Hillary Clinton is trying to dispatch Obama by making people afraid that he won’t keep America safe, and afraid that they won’t have health insurance if they don’t vote for her. She’s also worked hard to make Democrats afraid that Obama’s national security credentials make him an unable to beat McCain. Why is Hillary more compelling than Obama on NAFTA? It’s because she’s willing to play on people’s fears of foreign workers taking their jobs. President Bush’s entire political strategy has been to keep people in fear.

Because Obama is unwilling to go that route, he gives away the votes of people who respond most passionately to those emotions. That’s my theory, anyway.

Matt Raible on picking a framework

Matt Raible (now a full time employee of LinkedIn) posts about how he came to work there as a result of a consulting project where he helped them evaluate open source web frameworks against a framework that they had built in-house. In the end, he recommended enhancing their internal framework to include some of the best attributes of the open source frameworks, and he was hired to build a team to do just that. Anyway, the post contains a lot of wisdom about making these kinds of technology decisions.

The developer’s conception of time

I realized today that for me there are only two time horizons. There is “same as forever,” which is any period of time that seems like more than enough to finish whatever I have to do before my deadline, and there’s “not enough time to finish,” which is any shorter amount of time.

OpenAIM

AOL has officially AIM to third party instant messaging clients under an initiative called OpenAIM 2.0. There’s now a documented API that IM client writers can use to interface with AIM. Before, software developers reverse engineered the protocol used by the official AIM client and updated their software whenever AOL made changes that cut them off.

Hopefully this is one more step toward federation among services.

Against TDD orthodoxy

Google developer Cedric Beaust argues that treating orthodox Test Driven Development as some kind of panacea is a mistake, a position that I find it difficult to argue with. In fact, I find myself rejecting nearly all dogmatic software development philosophies. I like to read about them, but in the end I just steal the parts that work for me and do what seems to make the most sense.

My dirty secret: I almost never write a test, watch it fail, and then fill in the code necessary to make the test pass. That seems gratuitous to me.

Older posts Newer posts

© 2024 rc3.org

Theme by Anders NorenUp ↑