Posted By

bigeasy on 03/31/09


Tagged

javascript jquery


Versions (?)

jQuery Plugin: Extend $.get to parse plain text properties file to a hash


 / Published in: JavaScript
 

URL: http://blogometer.com/

  1. (function ($) {
  2.  
  3. // Keep a copy of the old get.
  4. var jQuery_get = jQuery.get;
  5.  
  6. jQuery.extend({
  7.  
  8. get: function( url, data, callback, type, options ) {
  9. // Shift arguments if data argument was omitted.
  10. if ( jQuery.isFunction( data ) ) {
  11. type = callback;
  12. callback = data;
  13. data = null;
  14. }
  15.  
  16. var actualCallback = callback;
  17. var actualType = type;
  18.  
  19. if ( type != null && type == "hash" ) {
  20. actualType = "text";
  21. actualCallback = function ( text ) {
  22. text = text.replace( /^\s\s*/, '' ).replace( /\s\s*$/, '' );
  23.  
  24. var parameters = text.split( /\n/ );
  25.  
  26. var hash = {};
  27.  
  28. for ( var i = 0 ; i < parameters.length ; i++ ) {
  29. var pair = parameters[ i ].split( /=/ );
  30.  
  31. var name = unescape( pair[ 0 ] ).toLowerCase();
  32. var value = pair.length == 1 ? "" : unescape( pair[ 1 ] );
  33.  
  34. var parts = name.split( /\./ );
  35.  
  36. for ( var j = 0 ; j < parts.length - 1 ; j++ ) {
  37. if ( hash[ parts[ j ] ] == null ) hash[ parts[ j ] ] = {};
  38. hash = hash[ parts[ j ] ];
  39. }
  40.  
  41. hash[ parts[ parts.length - 1 ] ] = value;
  42. }
  43.  
  44. var populate = function( hash, paths, builder ) {
  45. for ( var i = 0 ; i < paths.length ; i ++ ) {
  46. var parts = paths[ i ].split( /\./ );
  47. for ( var j = 0; j < parts.length - 1; j ++ ) {
  48. if ( hash[ parts[ j ] ] == null ) hash[ parts[ j ] ] = {};
  49. hash = hash[ parts[ j ] ];
  50. }
  51.  
  52. if ( hash[ parts[ parts.length - 1 ] ] == null )
  53. hash[ parts[ parts.length - 1 ] ] = {};
  54. }
  55. }
  56.  
  57. if ( !options ) options = {};
  58. if ( options[ 'hashes' ] ) populate( hash, options[ 'hashes' ], function () { return new Object() } );
  59. if ( options[ 'arrays' ] ) populate( hash, options[ 'arrays' ], function () { return new Array() } );
  60.  
  61. callback( hash );
  62.  
  63. }
  64. }
  65.  
  66. jQuery_get( url, data, actualCallback, actualType );
  67. }
  68.  
  69. });
  70. })( jQuery );

Report this snippet  

You need to login to post a comment.