Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
CHAPTER 10 Extending jQuery This chapter will give you the knowledge required to write plug-ins for jQuery. One of the really powerful features of jQuery is that you can add extra functionality easily using its plug-in framework. If you have some code that you are using frequently in your jQuery solutions, then it may be time to look at turning it into a plug-in and expose some options to allow it to suit a variety of scenarios. You are probably familiar with the Don't Repeat Yourself (DRY) coding practice, and plug-ins can help by making sure that repeatable code is put into a plug-in where it makes sense. The other thing to consider is that plug- ins can be used to do a huge range of really useful things. In fact, plug-ins can be used to do anything that jQuery can do, such as visual effects, utilities, DOM manipulation, and a whole lot more. Writing plug-ins can be a tricky concept to learn, but in this chapter, you will learn how to create a working plug-in. Instead of just learning theory, you will be working through lots of hands-on examples to build your first plug-in. Creating Your First Highlighter Plug-in The first plug-in you will create will simply highlight elements that match the jQuery selector. This will be a nice introduction to writing plug-ins and a good way to learn the basics before moving onto some of the more complicated components. The plug-in file is a JavaScript file, but as you will see, there is some different coding needed to create the plug-in. To develop this plug-in, we will use a Visual Studio solution that will deploy and activate the plug-in. You can use this method to deploy your own plug-ins or third-party plug-ins. Follow these steps: 1. Open Visual Studio 2010 and use the Empty SharePoint Project template to create a project called MyjQueryPlugins. Select "Deploy as a farm solution." By deploying it as a farm solution, you are making it available across the farm, and there will be only one copy of the plug-in's JavaScript file. Add a SharePoint Layouts mapped folder, as in Figure 10-1.x 2. 227