How to Write a jQuery Plugin – Part 1: Structure

One of the most beloved features of jQuery is that it is easily extensible. It requires little overhead to get a basic plugin started and it allows you to build reusable components on top of the power of jQuery. jQuery is already in use on many sites around the web. Creating a plugin allows you or other developers to easily drop your code into a site and start using it quickly.

Over the following three weeks, I will show you how to structure a basic plugin, provide a base set of features and how to package up and use your plugin on a page. Let’s get started this week with the basics of plugin structure.

Basic Structure

(function ( $ ) {
	$.fn.highlight = function (options) {
          // Our plugin code goes here.
	};
}( jQuery ));

The code snippet above outlines the basic structure of a jQuery plugin.  This may look out of the ordinary to you if depending on how you have worked with JavaScript in the past.  Let’s break it down.

Attaching to jQuery

Our plugin begins on line 1 with some strange syntax for declaring a function inside of parentheses.  At the end of the function’s brackets we have the “jQuery” variable in parentheses.  What’s up with that?

This takes advantage of a behavior in JavaScript called Immediately Invoked Function Expressions.  (I won’t go into detail about all that can be done with IIFE, but you can find more information here.)  The purpose of this code is to make sure that your plugin will work side-by-side with other libraries.  There are many libraries that use the $ character to provide an alias or shortcut (jQuery and ASP.NET AJAX are just two of many).

The last line of our plugin immediately passes the jQuery function into our IIFE, allowing us to use the $ alias within the scope of our plugin whether it is in use by another library outside of the plugin or not.

Plugin Declaration

On line 2 of the code above, we declare the $.fn.highlight function.  This is the main entry point of our jQuery plugin.  The function declaration also includes a parameter called “options”, which we will deal with in later parts of the series.

By attaching our function to $.fn, this makes it available anywhere in your application that jQuery is in scope.  You will likely recognize the syntax below that we can now use to call our plugin.

$(function () {
	$('p').highlight();
});

On page load, this will call the highlight function in our plugin for every paragraph tag on the page.  Feel free to try it out.  To run the code properly, you will need to include the plugin code in a file and include jQuery in your HTML file as well.

At this point, we have no code in our main function, so nothing will execute when our plugin is called.  However, in later installments we will add our plugin functionality and work with user defined options.

Thanks for reading!  Feel free to leave a comment or share this post.  Please come back next week for part two!

From the Bookmarks Bar – July 26, 2013

This week I’ve got a good mixture of links from the bookmarks bar that range from development tools to a “How It Works” to a little bit of programmer humor.  Without further ado, here they are:

How HTTPS Works

Ever wondered how such an open standard could possible be secure?  You’re not alone.  Here is an A-Z look at how HTTPS works.

Regular Expression Visualizer

There are many tools for visualizing regular expressions on the web, but I like this tool because of how clean the output is.  It’s simple enough to provide a great view of basic expressions, but expands well for those that are more complex.

Common Developer Interview Questions

No matter how long you have been in the game, it is always beneficial to brush up before an interview.

Things Only Developers Find Funny

It’s always nice to end the week with some humor.  Here are some great programmer jokes, including some that I’ve never seen before.

That’s another look at some links from the bookmarks bar.  Thanks for reading!  Have a great weekend!

Getting Started with the Stripes Framework

Stripes is an up-and-coming alternative to Apache Struts for developing web applications using Java. Stripes is very well documented, but leaves something to be desired in their sample projects and jump start information.  I’ve also noticed that while some of the features of Stripes are very extensible, it can be hard to understand what is needed and what isn’t.  I’ve included a quick briefing on some of the common pitfalls below.

ActionResolver

ActionResolver is a component of Stripes that discovers your ActionBeans and maps them to URLs for you to use in your views. One common mistake that occurs when setting up a new Stripes project is not having the ActionResolver properly mapped to the package containing your ActionBeans. This is done in the web.xml configuration file for your project.

<filter>
	<display-name>Stripes Filter</display-name>
	<filter-name>StripesFilter</filter-name>
	<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
	<init-param>
		<param-name>ActionResolver.Packages</param-name>
		<param-value>{Your ActionBean package name goes here.}</param-value>
	</init-param>
</filter>

If this is not configured properly, you may see errors such as this: “Could not locate an ActionBean that was bound to the URL. Commons reasons for this include mis-matched URLs and forgetting to implement ActionBean in your class.” This can be misleading because the actual cause is related to neither of those reasons.

UrlBinding

One particular difficulty that I had when I started working with Stripes was the usage of UrlBinding annotations. The reason for this is that if your ActionBeans are named properly, then you may never need to use them.

For example, let’s say you have an ActionBean class named LoginActionBean. By default, the ActionResolver will automatically bind this to the Login.action URL without any manual configuration required from you. The only time you ever need to use a UrlBinding is if your URL needs to differ from the automatically generated URL.

This is important to know, because at times the error messages returned by Stripes when it is not configured properly, such as the ones above, can lead you to using a UrlBinding even when you don’t need it.

Using HTML5/Custom Attributes

If you try to use custom attributes with one of the Stripes jump start projects, you will find that using HTML5 or other custom attributes will cause an exception to occur in Stripes.

For example, if you want to add an HTML5 placeholder attribute to a text input that is generated by Stripes, you will not be able to do it with the standard Stripes tag library.  This is also the case with JavaScript event attributes such as “onclick” or “onchange”, and custom attributes prefixed with “data-“.

I found the solution difficult to track down, but all you need to do is use the dynamic tag library provided with Stripes.  To use the Stripes dynamic tag library in your project, just add this taglib reference to the top of your JSP file:

<%@ taglib prefix="stripes" uri="http://stripes.sourceforge.net/stripes-dynattr.tld" %>

You can use the standard Stripes tag library and the dynamic tag library together on the same page.  You just need to set the prefix value in the code above to something different than the prefix value you are using for the standard tag library.  This is actually the recommended usage of the dynamic tags, yet it is not used in any of the current Stripes samples.

Never fear

Stripes is a lightweight framework that is great for developing Java web applications. Not many people are using it, and unfortunately that means that there are not many resources available outside of the documentation. However, the documentation is very detailed and technical. The process of getting up to speed may take longer than usual, but having an alternative framework to available is great for the future of Java on the web.

More information, including samples and comparisons to Struts can be found at http://www.stripesframework.org.

From the Bookmarks Bar – July 19, 2013

This week the bookmarks bar has some design and licensing links in addition to a couple of development related links.

Choose a License

Struggling to choose an open source license for your intellectual property?  Answer a couple of questions about your project and this site handles the hard part for you.

Redesigning a Flight Search Application

Rarely do we get detailed look at the redesign of such a data rich application.  We’ve all used a flight search site at one point or another and know how complicated they can be.  Here is Cleartrip’s development log of the process.

Comments in Modern Software Development

The opinion on the usage of comments has changed over time.  Comments used to be absolutely entirely necessary to understand a block of code, but many developers have since turned to better naming and segmentation to take the place of comments.  Here are some additional things to think about regarding comments.

WebAPI in ASP.NET MVC 4

ASP.NET MVC may not seem like the ideal choice for a small WebAPI project, but you can make it work.  Here is a good tutorial on the setup process.

Have some great links from your bookmarks bar that you like?  Post them in the comments below!  Thanks for reading.

System.Web.WebPages conflict between ASP.NET MVC 3 and ASP.NET MVC 4

After installing ASP.NET MVC 4, you may notice that you are unable to load projects that used previous versions of ASP.NET MVC. You may see an error similar to the following:

The type ‘System.Web.Mvc.ModelClientValidationRule’ exists in both ‘c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll’ and ‘c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages.dll’

This error occurs because prior to MVC 4, projects did not specify which version of ASP.NET Web Pages to use, since there was only one. Luckily, the fix for this is as simple as updating the project file to the proper reference of System.Web.WebPages. Many developers have not ever needed to modify a project file directly, since the default Visual Studio configuration is often sufficient. This can make editing a project file an intimidating task, so I have assembled detailed steps to solve the problem.

From the Solution Explorer, right click on the project and click “Unload Project” from the context menu.

The "Unload Project" menu item in Visual Studio 2010.

The “Unload Project” menu item in Visual Studio 2010.

You should see that the project is now marked with (unavailable). Right click on the project again and you should be able to select a new item, “Edit {Your Project Name}.csproj”. The extension will be displayed as .vbproj for VB.NET projects.

The "Edit Project" menu item in Visual Studio 2010.

The “Edit Project” menu item in Visual Studio 2010.

An XML configuration file will open. This contains all of the information that tells Visual Studio how to run your project. Scroll down (or search the file) until you find the following line:

<Reference Include="System.Web.WebPages"/>

Replace that entire line with this:

<Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>

Save the changes to the project file. Right click the project name in the Solution Explorer again. This time, select “Reload Project”. Your project will reopen in Visual Studio and should now build and run properly.

In simple terms, what we have done here is update the Reference tag to include version information, which resolves the conflict for Visual Studio.  It now knows which version of System.Web.WebPages you intend to use for your project.

Thanks for reading.  Still having trouble resolving the error?  Feel free to leave me a comment below!

From the Bookmarks Bar – July 12, 2013

I’m going to give something new a shot here.  From the Bookmarks Bar is a weekly round-up of interesting software development related links from around the web.  In general, it’s just a collection of things that I think you may find interesting.  Without further ado, here some favorites From the Bookmarks Bar for this week:

New Programming Jargon

We’ve all run into these issues from time to time.  This article reads like a book of the best programming related jokes.  Smurf Naming Convention is my favorite.

Raspberry Pi Powered Microwave

Disappointed by the lack of features on your microwave?  Why not overhaul it by integrating a Raspberry Pi?

The Visitor Pattern Explained

Many developers have only a brief understanding of the visitor pattern even after using it.  This is a detailed and practical example of the usage and practices of the visitor pattern.

How to Modify Bootstrap Simply and Effectively

Here is a collection of some great Bootstrap mods as well as some tools to easily modify Bootstrap to your tastes.  Want to make your Bootstrap based site look like Facebook or Metro in Windows?  An add-on can make it happen.

Super Mario Bros. 3 Match Game in Javascript

This is a fun one.  A developer has built a slick recreation of the match game from Super Mario Bros. 3, written entirely in JavaScript.  The project is well segmented and structured and is a good example for those looking to learn modern JS.  Source code is available here:  https://github.com/callmehiphop/mario-cards

That’s it for this week.  I’ll be experimenting with From the Bookmarks Bar over the next couple of weeks.  Feel free to leave a comment and let me know what you think.  Thanks for reading!

Dynamic Font Size (and other styles) in an Android App

I was recently tasked with adding the ability to change font size globally through the user’s selection in the application settings panel. Android provides accessibility settings on the device level that allow you change the font size for all apps on the device. This is made easy to implement in your app through built-in structures in Android, but documentation is not specific on the most efficient way implement this on an application level. This is likely to be because it is not an encouraged practice, but in my particular case, the requirements were that this needed to be changed in the settings for the application since more options would be available than the standard usability features of Android provide.

SharedPreferences

The key to storing settings in an Android application is SharedPreferences. The examples below do not demonstrate how to write values using the SharedPreferences editor, just how to retrieve them. For more information on writing to SharedPreferences, see this article.

The case against subclassing TextView

Do a quick Google search on implementing a global font size in code and you’ll see many responses suggest to subclass TextView and load the text size options there. Then all you have to do is make sure you use this class for every TextView in your layout. Simple enough, right? Will this work? Absolutely. Is this option going to cause more trouble than its worth as development on your app becomes more complex? Definitely.

The problem here is that many of the Android widgets subclass TextView, such as Button, RadioButton, and CheckBox. Some of these are indirect subclasses of TextView, which makes implementing your version of TextView in these classes a pain. Not to mention the trouble that could arise from migrating to newer versions of Android in the future.

Styles vs. Theming

As you may already know, you set styles for your layouts to control the look and feel of the view. Themes are essentially just collections of these styles. Theming can often be ignored by developers because it is seen more as a method for controlling collections of styles and not just a single style like text size. Many developers think, “I like the default Android theme, so I don’t need to worry about configuring themes.” However, you can use a theme just for text size settings; they don’t need define values for every property. Using a theme over styles provides us with one huge advantage: we can set a theme for the entire view programmatically. Without this, we would have to traverse the tree of children in the view and set each style using the associated property. With multiple properties to change and multiple nested child views, this can get complicated.

Example

First, we need to define the settings in our themes.xml file. This file normally resides in the “res/layout” folder within your application. If it does not exist, you can create it. Here I only use options of Small, Medium and Large, but we could easily add many other options here if necessary. Here is an example:

<resources>
	<style name="FontSizeSmall">
		<item name="android:textSize">12sp</item>
	</style>
	<style name="FontSizeMedium">
		<item name="android:textSize">16sp</item>
	</style>
	<style name="FontSizeLarge">
		<item name="android:textSize">20sp</item>
	</style>
</resources>

Then we will create a class to handle loading our preferences. I called it FontSizeActivity, you could call it ThemedActivity if you are setting more values than just the font size.

public class FontSizeActivity extends Activity {
	@Override
	public void onStart() {
		super.onStart();

		// Enclose everything in a try block so we can just
		// use the default view if anything goes wrong.
		try {
			// Get the font size value from SharedPreferences.
			SharedPreferences settings =
				getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE);

			// Get the font size option.  We use "FONT_SIZE" as the key.
			// Make sure to use this key when you set the value in SharedPreferences.
			// We specify "Medium" as the default value, if it does not exist.
			String fontSizePref = settings.getString("FONT_SIZE", "Medium");

			// Select the proper theme ID.
			// These will correspond to your theme names as defined in themes.xml.
			int themeID = R.style.FontSizeMedium;
			if (fontSizePref == "Small") {
				themeID = R.style.FontSizeSmall;
			}
			else if (fontSizePref == "Large") {
				themeID = R.style.FontSizeLarge;
			}

			// Set the theme for the activity.
			setTheme(themeID);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

Finally, we extend our existing Activity classes with the new FontSizeActivity, like this:

public class AppActivity extends FontSizeActivity {

Caveats

Yes, I know. I plead the case against subclassing TextView and then I ended up subclassing Activity for my example. What gives? Think of it this way; you should have a much fewer amount of Activities in your application than you do TextViews or widgets that inherit TextView. This will be exponentially so as complexity increases, so this solution requires less changes in code for you. In addition, the built-in subclasses of Activity are much less commonly used than the subclasses of TextView. You will need to extend those activities as well, but again they will ultimately require less code.

Conclusion

I’ve fought with all of the other ways to allow style based settings in Android and none of them have even come close to being this easy to implement. It is important to consider future changes to your application and this solution handily beats the other options in that regard. Thanks for reading.