3. jQuery plug-ins Two types of plug-ins: Utility functions jQuery.map( array, callback ) jQuery commands $( " p " ).click( function )
4. An example of writing a little plug-in Spock * A jQuery command which will (hopefully) find proper nouns in the elements' text and wrap them in a span with a class of keyword. $( " p").spock(); * I was watching an episode of Star Trek at the time.
5.
6. 1. Create a file for the plug-in Naming convention: jquery.plug-in-name.js In Spock's case: jquery.spock.js
9. 2. Make a closure All plug-in code should be within a closure. Pass jQuery to the closure and alias it to $ . This allows you to safely use $ within your plug-in code (and not worry about clashing with other libraries or frameworks who use $ too). (function ($) { // 1227 plug-1n c0dez go here })(jQuery);
13. 3. Define the jQuery command Extend the $.fn object. * (function ($) { $.fn.extend({ spock: function() { // Stop. Hammertime! } }); })(jQuery); * $.fn is an alias for the prototype property of the jQuery constructor function.
18. 4. Return jQuery wrapped set jQuery hackers don't want their chains broken. $("#jQuery") .find("haxors") .give("wine") .and("cheese"); Return a jQuery wrapped set so your plug-in can take part in the chain: return $(this);
24. 5. Set up options hash Users of the plug-in will want to configure it. Set up a hash of defaults and allow them to be overridden by options passed to the plug-in function when it's called. $("p").spock({ spanClass: "encino-man" });
25. 5. Set up options hash (function ($) { var opts; $.fn.extend({ spock: function( options ) { opts = $.extend({},$.fn.spock.defaults,options); } }); $.fn.spock.defaults = { spanClass: "keyword" }; })(jQuery);
40. 7. Events Your users will probably want to customise functionality. Assign a private method to a default option. Call the method through its option property. This way the users can hook into events via the options hash. $("p").spock({ processKeyword: function (match) { return "<strong>"+match+"</strong>"; } });
41. 7. Events $.fn.spock.defaults = { processKeyword: processKeyword }; function processElements () { // ... return opts.processKeyword(match); // ... } function processKeyword (match) { // Kiss my aura, Dora. }
42. Thanks The Spock code is on Github: http://github.com/DylanFM/jquery-spock I'll put these slides online and tweet it through: @dylanfm