Tuesday, January 13, 2009

Javascript for Facebook

Facebook, Inc.Image via WikipediaJust spent some time with Facebook's Javascript replacement, FBJS. Its a must if your Facebook app has complex things to do.

FBJS rewrites all of your method and variable names so your code is confined to a sandbox and cannot mess with any of Facebook's code.

This renaming confines your code to a document called "aXXXXX.document", where "XXXXX" has to be your Facebook app's numeric id. So if you have this code:

document.getElementById('choice2_info')

Facebook changes it to this:

a19756161464_document.getElementById('choice2_info')

You can see this if you look at the source for the page finally presented by Facebook.

You'll also see that the id attributes for HTML elements are also changed in the page source. The original attribute may have been:

id="choice1_option_id"

but is actually rendered as:

id="app19756161464_choice1_option_id"

When using making use of methods and id, your code should use the originals, not the replacements. The FBJS version of getElementById will add the appropriate prefix to whatever you pass it, so it will look for an element with the id "app19756161464_app19756161464_choice1_option_id" if you prepend the id first.

FBJS also requires that you use different method names than you would if you are writing straight Javascript. For example, instead of using ".target" to look at or change an element's target, you use ".getTarget" or ".setTarget".

You can see a list of the methods affected here. There is much more on FBJS on that page and I highly recommend reading and understanding the material there before beginning a project.

If you do anything complex, you'll probably want to use a tool like Firebug to set breakpoints and watch the values of key expressions. I had a lot of trouble with the newest version, but version 1.2.2 worked fine.


Reblog this post [with Zemanta]

No comments: