Alchemy and the Dangers of JQuery Scope

While working on a plugin with Alchemy recently, I noticed something helpful: my popup window automatically inherited the Tridion CSS and JS. This is especially great if, like me, you want to make a popup look like Tridion. However, it did raise one concern. GUI extensions often rely heavily on JavaScript, and if, like me, you’re a Tridion developer who dabbles in JS you might not be that familiar with JavaScript variable scope. There is a tonne of information available online on this subject, but I wanted to bring attention to it in the context of Tridion and Alchemy.

When working with JavaScript one of the first things I tend to do is to define a few variables that I need throughout my file. These are variables that I need access to in a number of different functions and are known as “global” variables. The danger with these global variables is that if they happen to share names they can trample over each other, overwriting important variables in use elsewhere in Tridion. As you can imagine, once you have a large number of Alchemy plugins installed (and you will want a large number of Alchemy plugins installed!), you’re in danger of them stepping on each other and basic Tridion functionality.

There are a number of ways to avoid these issues as a plugin developer, but my favourite is to enclose your JavaScript files in a self-executing function. This looks like:

!(function () {
“Your Plugin’s Javascript”
})();

How does this help? In JavaScript the scope of a variable is only it’s function, meaning that by running all of our code inside a function we are keeping all of our variables to just our own plugin. This greatly reduces the chances of overlap and helps to keep all of our plugins playing together nicely.

Those of you already familiar with these self closing functions may be wondering about the leading exclamation point on mine. Tridion bundles and minifies its JS and in the process it removes semicolons, meaning that if the previous JS file being bundled ends in a parentheses it can interpret this () as a function type and attempt to execute it with your self-executing function causing errors. By inserting an exclamation point your self-executing function gets interpreted as a grouping and this issue won’t arise.

Long story short, as with most great things in life, writing JavaScript for your plugin is safer with a protective wrapper.

Hat tip to Alex Klock for helping me with the material for this post. Check out his blog here for more genius level Tridion writing.

One thought on “Alchemy and the Dangers of JQuery Scope

  1. Pingback: Setting Alchemy Plugin Permissions | SDL Tridion Developer

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>