A Lesson on JavaScript Objects and Prototype’s bindAsEventListener Method

This post covers 3 topics about JavaScript:

  • How objects work in JavaScript and what makes them useful.
  • A concise explanation as to why the this variable is confusing at times.
  • A clear explanation of bindAsEventListener since the official one is confusing at best.

An Overview of JavaScript Objects

To dumb things down, in JavaScript, functions can be assigned to variables. Thus, you can do cool stuff like this:

var eat = function() {
    alert(‘munch, munch’);
// displays ‘munch, munch’

Objects are denoted by using curly brackets. Inside an object, you can put variables. The syntax is a little different, so pay attention. Thus:

var Michi = {
    favoriteFruit: ‘banana’,
    favoriteBread: ‘whole grain’
// displays ‘banana’

Note: I don’t like either of those that much.

The colon is sort of an equals sign. It essentially equates to “variable name: value”. Each assignment is separated by a comma and the “value” portion can be anything that you can assign to a regular variable. Since you can assign variables inside objects, that means you can put functions inside objects. Then you can call a function by putting a pair of parentheses () on the end of the variable. Again, pay attention to the syntax:

var Michi = {
    eatFruit: function() {
        return ‘Eating: banana’;
// displays ‘Eating: banana’

In a truly object oriented example, calling eatFruit() should cause Michi to eat his favoriteFruit variable:

// does the same thing as the previous example
var Michi = {
    favoriteFruit: ‘banana’,
    eatFruit: function() {
        return ‘Eating: ‘ + this.favoriteFruit;

This is where stuff gets sticky. Or maybe gooey. Nah, I won’t make a pun here. this refers to Michi. This is important because later we might copy Michi into another variable Tom. When that happens, this now refers to Tom‘s favorite fruit, which might be an orange. this is a dynamic placeholder for whatever object that we are inside of.

How *this* Complicates Things

Let’s continue illustrating the problem by building another example:

function watch(personEating) {
// displays “Eating: banana”

This will do exactly what you think it will do. It will cause Michi to eatFruit(). However, the next example is where things get very tricky:

function watch(personEating) {
// the goal is to display “Eating: banana”

This will fail. Why? Notice the very subtle differences between the two examples. Look at section I highlighted. In the first example, the function is called and its result, the text “Eating: banana” is then sent to alert(). In the second example, the function Michi.eatFruit is passed in as a variable. It is then called as a function from inside watch(). Translated, that code renders like this:

function watch(personEating) {
    // this temp stuff isn’t necessary, but it should make
    // things easier to understand

    var tempFunction = function() {
        return ‘Eating: ‘ + this.favoriteFruit;
    var tempText = tempFunction();

As you can see, the problem is due to the this.favoriteFruit variable. this now refers to the function watch()‘s parent (e.g., nothing at all), which doesn’t have a favoriteFruit variable. this no longer refers to Michi. This is a very common and very frustrating part about JavaScript. To get around this, the popular prototype library has a fix.

Prototype’s bindAsEventListener

The official documentation (as of this writing) for this method is dead wrong. Their example is wrong. Their explanation is fuzzy. Maybe somebody over there will read this and fix it up. Prototype’s example doesn’t even work! The corrected example is:

var obj = { name: ‘A nice demo’ ,
    handler: function (e) {
        var tag = Event.element(e).tagName.toLowerCase();
        var data = $A(arguments);
        alert(this.name + ‘\nClick on a ‘ + tag + ‘\nOther args: ‘ + data.join(‘, ‘));
Event.observe(window, ‘click’, obj.handler.bindAsEventListener(obj, 1, 2, 3));

So I will try to explain how to use it correctly. The syntax is simple:


Thus, in my previous example that broke, you would rewrite it as follows:

function watch(personEating) {
// was watch(Michi.eatFruit);

When the code is executing, it knows that this refers to Michi, thanks to that argument being passed in. The argument represents what this refers to. So you would still call the method exactly as you normally would, but you tack bindAsEventListener on the end.

I hope this was educational. The fixed demo code will run for certain since I tested it; the rest: I am not as sure (95%).

REMEMBER: Word Press likes to convert my quotation marks into the slanted ones. So if you cut and paste my code, make sure you change those!

Sony Planned to Upgrade the PS3 but Microsoft Beat Them to It

I find this infuriatingly stupid: Sony has (inadvertently) revealed plans to release a new PS3 that has a 80Gb hard drive. It’s not that I don’t like the upgrade; I don’t agree with the decision to upgrade now. A product that has been in the market for barely 6 months (wait, no, it hasn’t) is not ready for an upgrade. It was only released this week in Europe!

Why in the world are they trying to upgrade the hardware? To attract more buyers? Allow me to point out a simple flaw in their reasoning:

  1. Build the biggest and best console
  2. Wait for people to come buy it by the cart full
  3. Realize sales are tepid and panic
  4. Make the biggest and best console even “better” by upgrading it
  5. Wait for people to come buy it by the cart full

It’s a commonly known fact that the “if you build it they will come” strategy is poor at best. And clearly, they built it and they didn’t get anywhere near what they thought they’d attract. Now they hope on attracting more people by following the same retarded logic from the first time around. By starting this measure so early, they risked a leak. And boy did it leak. So now anybody thinking about a PS3 has a real incentive to wait. I mean how mad would you be if you bought a 20Gb PS3 only to have it “discontinued” the next day? Good way to slow your sales there, Sony.

And what about the increased cost of the drive? Why add $5 per machine when you could save that difference and get your product to stop bleeding away your hard earned profits. What’s 20Gbs anyway? If you’re going to do an upgrade, at least do it like Microsoft and go big (120Gb). Not to mention the upgraded 360 comes in its own color, allowing for extra bragging rights to adopters.

Sony is approaching this all wrong. They made critical assumptions when designing their product which turned out to be wrong. But instead of correcting those mistakes, they continue down the same path. In constrast, Microsoft is doing an amazing job. They resisted the urge of bundling the HD-DVD player. Microsoft has a lot to gain by the HD-DVD format becoming accepted, but they recognize that bundling the player for $200 would be a critical error that will price them straight out of the market.

I don’t think Sony realizes it yet, but they are boxing at Microsoft’s pace. And Microsoft knows exactly where they’re headed, while Sony seems to be caught off guard more and more frequently. Now, it looks as if the 360 is a far better deal, coming with nearly double the capacity of the lower model for less money. If there’s one measure any consumer can understand, it’s hard drive capacity.

This may also be Microsoft’s power play to get Sony to match them at 120Gb, in hopes of further increasing the cost of PS3 production and hurt Sony’s bottom line. Sony can’t possibly raise the price of the PS3, so they’d have to eat the added costs. That, or they let Microsoft take the crown for disk capacity. This is an extremely difficult move for Sony to mimic. In short, it is a deviously smart business move by Microsoft.

How I Choose What I Write About

Today’s real update will have to come in the afternoon seeing as I’m exhausted right now. 🙂 There was once a time when working 16 hour days didn’t phase me. It sucks to get old! Well, and it’s 3am.

Since I’m nearly brain-dead now, I thought I’d keep this one simple and give you guys a little bit of insight on how I pick what I write about each day:

  1. If I encounter a really hard programming problem at work, I will blog about the solution. These posts drive my search traffic.
  2. Programming posts don’t count toward my goal of one post each weekday. Weekends posts are a bonus to my readers. When I do a programming post, I couple it with a second post. Only when you are really unlucky (or lucky, depending on who you are) will that second post also be a programming post.
  3. I often skip coverage of major developments that have no real insight to add. For example, I recently skipped coverage of Dvorak’s anti-iPhone post (he’s dumb, and everybody knows it), YouTube’s new live chat feature (cool, but important), and developments in the RIAA lawsuits (they’re losing). My logic is that I only have about one hour a day (tops) to commit to a post so I might as well pick a good topic.
  4. My favorite companies to write about are: Google, Apple, Microsoft, and Yahoo. These companies have their hands in many industries, and it is interesting to see how they juggle their competing internal interests. Better yet, it is fascinating how they bring them together.
  5. I try to put double thought into one post a week. Last week was my YouTube post. This week was my stats post (or maybe my Yahoo or Google Checkout post). My goal is to write something good enough that I will gain one new regular reader a week. 🙂
  6. If I see news about e-paper, I will very likely post about it. As I’ve said before, I believe this technology will become as pervasive as the LCDs in the next decade. If there’s any technology outside of the web that I am a fan of, it is e-paper.

So if you have a topic you’d like me to cover more often, feel free to ask. Today, either later in the afternoon or evening, I will be writing about Sony’s further idiocy and how to submit better articles to sites like Digg. Yes, I’ve noticed some of you are submitting my work. I appreciate it, but it could be done better. 🙂

Microsoft Doesn’t Like it When People Piggy Back on Their Technology

Some companies thrive on the idea of having others utilize their service in new, creative ways. Facebook has an API. eBay has an API. Google has 20 APIs. People mash Google Maps and Craigslist. Yahoo just released a product which has the sole purpose of mixing content in ways that weren’t necessarily originally envisioned.

So now it’s Microsoft’s turn. I’m not saying they don’t have APIs. I’m not saying they don’t let people try new things with their technology. Although I’m also not saying they encourage it. Today, Microsoft confirmed that they have actually gutted an entire feature set out of their search engine because some minority of people are “abusing” it.

They’re essentially telling their power users to stop being power users.

I can’t say for certain if that’s incredibly stupid since I don’t know what exactly the “abuse” involved, but the demographic Microsoft is hurting here is potentially their biggest fans. The users who have taken the time to learn the intricate details of their advanced syntax are those that recognize a certain value in Live Search. When you take away the tools that these people have come to appreciate, you take away their reason to come back to your site.

In short, I think it’s a dumb move.

PHP Nuisance: How to Stream PDF Files

If you’ve ever tried to stream a PDF file in PHP, you know how incredibly annoying it is to get it working across all browsers. In fact, the maintainer of HtmlToPdf didn’t have an official response on the topic of streaming PDF data to the browser. It only worked most of the time. When it fails, the page loads the data, but nothing actually shows up and your PDF reader will not fire.

The very short explanation is that IE ignores certain content type headers and tries to guess what a file is based on its content. This is a problem in some situations when IE guesses wrong. God, IE is so dumb because it tries to be too smart. Don’t you hate people like that?

Anyway, to get it to work, you have to hack at it. There are added complications to this when you are using HTTPS instead of HTTP.

After we spent a few hours today at work trying to solve this problem, I remembered I had done this before. I dug up some old code and found the solution:

$filename = ‘yourfilename.pdf’;
header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: public”);
header(“Content-Description: File Transfer”);
header(“Content-Type: application/pdf”);
header(“Content-Disposition: attachment; filename=$filename”);
header(“Content-Transfer-Encoding: binary”);
// echo the pdf raw binary data here

As far as I know, this works in every browser. All you Googlers: Enjoy! 😉

Leave a comment if this worked! 🙂

The Down Side of Getting on Digg and Having Tons of Readers

Ever since I got Dugg and what not, I have had a ton more readers. I’ve gotten about 1,000 visitors a day now, many of which subscribed (hurray!). But my new boo-hoo “I’m not a princess” moment came when I looked at my logs for the month:

a mountain in a sea of no visitors

Reminds me of a mountain in the middle of a really barren, really flat desert. I shouldn’t complain, especially since this blog is 100% for-fun anyway.

Well, the real down side to having hundreds of readers is that I now have an implicit responsibility to update on a daily basis. 😉

If PS3 Broke Records in UK Why is it so Cheap on UK eBay?

Today’s post is about the PS3. I find the PS3 to be an interesting product because of its relative success despite its pricing and feature set that is contrary to the customer’s desires. In short, it has features most customers don’t want (Blu-Ray) and because of these features, it costs a ton more.

So imagine my surprise when the media started reporting that the PS3 sold out in Europe and, in fact, broke sales records in the UK.

I remember launch day in the US: every PS3 in sight was sold out and the Wiis barely ran out of stock. But then it was only a few weeks before demand revealed itself: everybody bought a PS3 so they could scalp it to the hardcore fans who didn’t have one yet. As a result, the PS3 aftermarket quickly died and the eBay market followed it. Soon, people were selling them for a loss!

And I remember Japan’s launch, when people were paying Chinese immigrants to stand in line and buy PS3s so they could sell them later. In fact, the story goes that the first person to ever buy a PS3 later walked from the store to a nearby parked car and gave it to his “boss.” It seems to me like the PS3 launch hype is largely due to scalpers.

So what about the UK? With all this record breaking nonsense, UK eBay must be booming, right? Here’s what I noticed after looking at 1423 closed PS3 auctions in the UK:

  • High prices (30% markup or more) were commanded by auctions that happened prior to March 25th (launch). This makes sense.
  • Only 55 closed auctions went or asked for a price above retail (£600).
  • Most that sold for a profit went for £650 (8% markup).
  • At £599 (retail), there were 95 auctions that went without any bids, three auctions for the PS3 that sold, and five auctions for the PS3 plus 3 games that sold.
  • There are countless pages of auctions below retail price going unsold (requires eBay login). £450 for a £599 console that came out less than a week ago? (see image below)
  • In contrast, searches for the Wii show approximately half of all auctions (maybe 60%) closed with a sale. Prices ranged a lot due to bundling, but a vanilla Wii was selling for approximately £300 (65% markup). In fact, at the £300 range (requires login), virtually every auction closed with a sale. And at the £250 range (requires login), the auctions had double digit bids.

check out those buy it now prices!I am not doing this to be scientific, but it’s a stark difference from the PS3 opening week in the US. Auctions ranged around $900 for the 60GB model, a 50% markup. I urge others to go confirm my observations. eBay is possibly the single best product demand barometer of our time. I know the PS3 broke records in UK, but then why isn’t the UK eBay demand following these figures? Is there low demand, except from scalpers?

If I’m wrong, the PS3 will continue to sell out in Europe and give Sony the boost it needs. But if I’m right, you should start seeing the negative “too much stock” stories in about 2 weeks when the eBay market reality sends thousands of scalpers back to the store to get refunds.

At the very least, someone explain all of these “buy it now” auctions that are set below the retail price.

An iPhone Post Not About Apple – The Sprint Phone

Sprint is releasing a new phone (wishfully called “UpStage”) that gives direct-to-phone downloads for $0.99. While everybody is quick to compare it to the iPhone, the first thing I thought of was the retarded Zune Phone rumor. Why? Because it is yet another flawed “me too” attempt that brings nothing new to the table (that consumers want — a key point). Wireless downloading does not suddenly make this phone “a significant challenge to the iPod maker!” How many times is the average phone owner going to buy and download a song? Five times a day? Five times a week? Five times a month? Seriously, the benefit of this feature is so insanely marginal, it baffles my mind that this company presses this as its “break through” feature. I don’t even know why it makes news. Fire your publicist and marketing team!

Aside from the bad Internet navigation UI (if it can even do that), it has two features that will keep it from ever taking over the market:

  • DRM that’s not Fair Play and likely not compatible with your computer.
  • Priced to compete as a commodity item.

Let’s break this down.

DRM that is not Fair Play is already suicidal, but on a phone, it’s double-doom. Nobody will buy music on a phone that will only play on your phone. Maybe the Sprint execs forgot that iTunes music plays on your computer, phone, iTV, and iPod? This would make these songs quite possibly the worst deal in digital music downloads (OK, that’s not true – ring tones are worse).

Commodity price comes with the commodity image: your product is what poor people buy if they want a half-decent phone. So while this phone might garner as much market share as the Chocolate or whatever other crappy already-existing “media” phones, it will never stand out. The only thing this phone has going for it is the “buy our DRM-songs over the air waves for $0.99!!!” Rip off. People will despise the idea of buying music at one online store (say, iTunes?) and then have to buy it again on the “Sprint store.”

Microsoft could make an entry here with their dumb Zune Phone. But if you haven’t already figured it out with my repeated bashing, this would be a monumentally moronic move on Microsoft’s part. They have significant share of the mobile phone market now; why waste it? Entering the market with their own branded phone would instantly turn all their partners into competitors – thereby killing any friendly deal making. Oh, and let’s not forget it would destroy their Zune market share since nobody would buy a Zune for $250 when they can get a Internet capable, Internet-Squirting Zune Phone for $200.

If Microsoft enters the mobile phone market chasing Apple, it would be karmic stupidity that rivals Sony when it got over-eager chasing Microsoft in the console market.

The phones best positioned to compete with the iPhone are not these entry level toys! Look to the $600+ market and you’ll see a slew of excellent premium phones. Stop comparing Fords to the BMWs and then call them competitors: nobody who buys a pick-up truck is in the market for an M5 and vice versa.

By the way, does this phone accept regular headphone jacks instead of those $14 proprietary ones? If it doesn’t, then I rest my case.

How I Integrated Dugg Mirror When I got Dugg

My regular readers probably didn’t realize, but I was recently on the front page of Digg, Slashdot, and Reddit. Digg and Slashdot are notorious for killing servers that get linked in their stories. If you want to see the stats for the days in question, you should see my post about it. This post is a little geeky, so beware.

Here’s the quick and dirty list for keeping your server up during a Digg Crisis:

  1. Download and enable wp-cache.
  2. Use the .htaccess rule I explain below. It keeps the rest of your site operational and even lets people post comments directly from the mirror!
  3. Turn off miscellaneous plugins. The biggest suspect was my related posts plugin (see below).

CPU Load

When I got on the front page of Reddit, my traffic spiked immediately. My server load went up to about 2.00. A “2.00” is high, but is manageable and won’t cause any real problems. A “1.00” approximately equates to “100% of CPU used.” So you can guess what a “2.00” means. Realizing Digg was coming next, I knew I had to start making preparations, since this graph shows just how much bigger Digg is than Reddit.

I knew my hits would increase 100x, so I had to shut down as much unnecessary stuff as possible. First, I wanted to turn off every plugin I had on Word Press and then activate wp-cache, which would significantly reduces database overhead. Unfortunately, before I was finished configuring the cache settings, I hit the front page of Digg in record time. The server became non-responsive and I couldn’t even hit the “enable” button. My server load sky rocketed past 500.00. At 500, things stop working.

Integrating Dugg Mirror

Dugg Mirror is a service that creates copies of articles that hit the main page of Digg. Their goal is to serve as a backup in case the main source goes down (as it often does). As soon as my server was Dugg, my objective was to forward all traffic to the mirror.

When my server died, I was racing against time to redirect the traffic. Until I redirected the traffic, I couldn’t do anything to mitigate the problem (such as disabling plugins). It took me about five minutes (due to incredible lag) to connect to the server, go to the correct directory, and edit the .htaccess file to add this line at the very top:

RewriteCond %{HTTP_REFERER} (digg.com) [NC]
RewriteRule maybe-google-wanted-to-be-sued-youtube-and-plan-b http://duggmirror.com/tech_news/Why_Google_wanted_YouTube_to_be_Sued/ [R,L,NC]

The first line says, “If this visitor is from digg.com”. The second line (wrapped over two lines) says, “then redirect hits to my google article to the Dugg Mirror.” This redirected everybody who came to my site from Digg that wanted to see my article to the Mirror. Note that the rest of my site worked completely fine, and anybody trying to post a comment directly from the mirror was able to do so.

Upon applying this fix, my server load dropped to 4.00.

To make this work for your dugg articles, use the following:

RewriteCond %{HTTP_REFERER} (digg.com) [NC]
RewriteRule [article URL without beginning/trailing slash or domain] [dugg mirror URL] [R,L,NC]

The Finishing Touches

I made sure my most CPU/MySQL intensive plugins were off when a digg user came (since they were the ones causing problems). I put a snippet of code around my related post plugin that looked like this:

<?php if(FALSE === stristr($_SERVER[‘HTTP_REFERER’], ‘digg.com’)) { 
/* Intensive plugin-code */
} ?>

This snippet basically says, “If this visitor is from Digg, don’t do the burdensome plugins.” The thinking is that if a visitor is coming from Digg, I am likely Dugg, so if I wasn’t lucky enough to see it coming, at least I will mitigate some of the problems.

I also disabled my anti-comment-spam plugins and only kept Akismet running (since I hear Techcrunch uses it). I also initially disabled Spam Karma 2, but I eventually turned back on (I prefer it over Akismet).

As a good example horror story of how a plugin can kill you, I once had the Bad Behavior plugin installed (late 2005). It completely locked up my database when several search bots hit the site because it attempted to log each and everything the bots did. It took me days to figure out my blog was taking down my entire server because of this plugin! (There is a new version out now, but I am too scared to try it now.)

Anyway, my point is for you to be careful with plugins that use the database and only use ones you absolutely need, especially when getting Dugg.

I then finished enabling my blog cache, and my server load fell to 1.00. My server was down for about 5 minutes total. Minutes later, I pointed the traffic back onto my site with Word Press caching enabled and the load sat around 4.00. I won’t know for sure, but I think my server would have survived had I enabled the cache plugin from the beginning (which I tried to do!! 🙁 ).

The next day, I was on Slashdot and my server never went down. This is why I conclude that not enabling the cache plugin had more to do with going down than any other factor.

Non-Word Press Administrators

Note that the web server was fine. MySQL failed. MySQL is much less robust than the web server when it comes to this sort of stuff, and requires significantly more baby-sitting. This is especially true for applications that weren’t designed to scale, such as Word Press. This is why the cache plugin is so powerful.

If you have a web application that is MySQL intensive and NOT Word Press, the steps you need to take to keep your site up are different:

  • Minimize the SQL running on the landing page that is getting Dugg. This may involve turning off things like session logging. For example, I turned off a user tracker that inserted a record into the database every time a visitor came to the site. Disabling this sped things up quite a bit.
  • Create as much static content as possible, at least for the first two hours. After the initial surge, traffic will drop to manageable levels (see hourly graphs near bottom). Your best bet is to “fake” part of your application with static content and a disclaimer to come back later.
  • Increase the memory usage limit for MySQL.
  • Increase the maximum allowed connections to MySQL.
  • Make sure you are using indexes in your queries. The quick and very dirty way of explaining this is if you have a SQL statement “… WHERE blah = ‘some value'”, make sure there is an index on the column blah if that table is more than 500 records and that column has many unique values (i.e., ignore columns like status, gender, or active/inactive). No, that’s not the ideal answer (this is why DBAs make the big bucks), but it’s the quick and dirty explanation why many Word Press plugins tend to contribute to a server dying when getting Dugg. Perhaps I will cover this in more depth another day.

I hope this helps!

Charts of Digg, Slashdot, and Reddit Traffic

Here are some numbers on the visitors brought in after I published my popular Google theory. Some of the most interesting stats:

  • Reddit and Slashdot generated nearly the same amount of traffic.
  • Only 74.8% of visitors use Windows (geeky crowd, part 1).
  • Firefox dominates with 65.5% (geeky crowd, part 2).
  • At the peak, I was using 3.0 Mbps when I hit the front page of Digg and Slashdot. I had about 2.0 Mbps sustained from each incident while I was at the top of the main pages.
  • The Reddit traffic surge is very gradual. It is difficult to assess exactly when I hit the front page of Reddit. I think this has to do with the fact that their site customizes the front page for each user. My money is on 4:15PM 03/20/2007 (see chart at bottom).

By siteVisitors by site:

  • Digg: 36,582 (of which 22,581 were redirected to Dugg mirror)
  • Slashdot: 14,961
  • Reddit: 9,296
  • Stumbleupon: 1,270

By day Visitor by day:

  • March 19, 2007: 332 (regular day)
  • March 20, 2007: 13,771 (Reddit front page)
  • March 21, 2007: 17,512 (Digg front page)
  • March 22, 2007: 17,321 (Slashdot front page)
  • March 23, 2007: 2,131
  • March 24, 2007: 1,404

Operating systems

Operating system:

  • 74.8% Windows
  • 13.4% Mac
  • 9% Linux

Bandwidth by day:

  • March 19, 2007: 26 MB (regular day)
  • March 20, 2007: 3,800 MB (Reddit front page)
  • March 21, 2007: 6,340 MB (Digg front page)
  • March 22, 2007: 6,460 MB (Slashdot front page)
  • March 23, 2007: 741 MB
  • March 24, 2007: 462 MB

Browsers Browser:

  • 65.5% Firefox
  • 19.7% IE
  • 5.3% Safari
  • 4.2% Opera

Bandwidth usage graphs:

Note, technically, I made front page of Digg at 10PM on 03/20/2007.

Traffic seems to heavily corresponds with work hours. 😉

Take note: this ordeal cost me almost 15 gigs of bandwidth for a text post. For those of you hoping to make a buck off of Digg, make sure you have no overage charges with your host. Also, make sure you can actually handle the traffic. The spike will bring down your entire server if you aren’t prepared.