Created
July 12, 2010 17:36
-
-
Save cowboy/472783 to your computer and use it in GitHub Desktop.
jQuery Pluginization (see comment for slide order)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
// Store fetched long URLs here. | |
var cache = {}; | |
$.longUrl = function( url, callback, options ) { | |
// Override defaults with specified options. | |
options = $.extend( {}, $.longUrl.options, options ); | |
var params = {}; | |
if ( cache[ url ] ) { | |
// URL exists in cache, so use it. | |
callback( cache[ url ] ); | |
} else { | |
params[ options.param ] = url; | |
// Fetch JSON data. | |
$.getJSON( options.api_url, params, function(data){ | |
if ( data[ url ] ) { | |
// If the data is valid, update the cache. | |
cache[ url ] = data[ url ]; | |
// Call `callback` for this element + long url. | |
callback( cache[ url ] ); | |
} | |
}); | |
} | |
}; | |
$.fn.longUrl = function( options ) { | |
// Override defaults with specified options. | |
options = $.extend( {}, $.longUrl.options, options ); | |
return this.each(function(){ | |
var elem = $(this), | |
url = elem.attr( options.attr ); | |
// Fetch long URL and call `lengthen` when done. | |
$.longUrl( url, function( long_url ){ | |
options.lengthen( elem, long_url ); | |
}, options ); | |
}); | |
}; | |
// Some sensible defaults. | |
$.longUrl.options = { | |
api_url: 'http://www.longurlplease.com/api/v1.1?callback=?', | |
param: 'q', | |
attr: 'href', | |
lengthen: function( elem, url ) { | |
// Update the element's title attribute with `url`. | |
elem.attr( 'title', url ); | |
} | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are the general steps, in-order: