Posted By

johnloy on 03/02/09


Tagged

javascript textmate design-patterns


Versions (?)

Way to programmatically override a config object for a module pattern


 / Published in: Other
 

  1. /*
  2. http://www.wait-till-i.com/2008/05/23/script-configuration/
  3. */
  4.  
  5. var module = function(){
  6. // configuration, change things here
  7. var config = {
  8. CSS:{
  9. classes:{
  10. hover:'hover',
  11. active:'current',
  12. jsEnabled:'js'
  13. },
  14. ids:{
  15. container:'maincontainer'
  16. }
  17. },
  18. timeout:2000,
  19. userID:'chrisheilmann'
  20. };
  21.  
  22. // start of main code
  23. function init(){
  24. changeConfig.set(arguments[0]);
  25. console.log(config);
  26. };
  27.  
  28. // … more methods and other code …
  29.  
  30. // Configuration changes
  31. var changeConfig = function(){
  32. function set(o){
  33. var reg = /./g;
  34. if(isObj(o)){
  35. for(var i in o){
  36. if(i.indexOf(’.')!== -1){
  37. var str = ‘["' + i.replace(reg,'"]["') + '"]‘;
  38. var val = getValue(o[i]);
  39. eval(’config’ + str + ‘=’ + val);
  40. } else {
  41. findProperty(config,i,o[i]);
  42. }
  43. }
  44. }
  45. };
  46. function findProperty(o,p,v){
  47. for(var i in o){
  48. if(isObj(o[i])){
  49. findProperty(o[i],p,v);
  50. } else {
  51. if(i === p){o[p] = v;};
  52. }
  53. }
  54. };
  55. function isObj(o){
  56. return (typeof o === ‘object’ && typeof o.splice !== ‘function’);
  57. };
  58. function getValue(v){
  59. switch(typeof v){
  60. case ’string’: return "’"+v+"’"; break;
  61. case ‘number’: return v; break;
  62. case ‘object’:
  63. if(typeof v.splice === ‘function’){
  64. return ‘['+v+']‘;
  65. } else {
  66. return ‘{’+v+’}';
  67. }
  68. break;
  69. case NaN: break;
  70. };
  71. };
  72. return{set:set};
  73. }();
  74. // make init a public method
  75. return {
  76. init:init
  77. };
  78. }();
  79. module.init({
  80. ‘container’:'header’,
  81. ‘CSS.classes.active’:'now’,
  82. ‘timeout’:1000
  83. });

Report this snippet  

You need to login to post a comment.