InitMirror.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * java代码脚本编辑器
  3. * <pre>
  4. * 在同一个页面可以渲染多个编辑器
  5. * 通过选择设置了codemirror="true"的textarea来渲染
  6. * 当前光标插入内容:InitMirror.editor.insertCode(str);
  7. * 设置所有内容:InitMirror.editor.setCode(str);
  8. * 保存编辑器内容到原来的textarea:InitMirror.save();
  9. * </pre>
  10. */
  11. if (typeof InitMirror == 'undefined') {
  12. InitMirror = {};
  13. }
  14. InitMirror.editor = null;
  15. InitMirror.options={
  16. randomRange:999,//key随机数范围
  17. editors:[], //编辑器数组
  18. height:"150px",
  19. lock:false,
  20. initDelay:0 ,//渲染延迟(不设置延迟渲染可能会与ligerui的布局初始化冲突)
  21. isCurrent:true
  22. };
  23. $(function(){
  24. setTimeout(InitMirror.init,InitMirror.options.initDelay);
  25. });
  26. //初始化
  27. InitMirror.init=function(){
  28. $("textarea[codemirror='true']").each(function(){
  29. var mirrorHeight=$(this).attr("mirrorheight"),
  30. key = InitMirror.getKey(),
  31. editor = CodeMirror.fromTextArea(this, {
  32. height: mirrorHeight||InitMirror.options.height,
  33. parserfile: ["tokenizejava.js","parsejava.js"],
  34. stylesheet: __ctx+"/js/javacode/javacolors.css",
  35. tabMode : "shift",
  36. path: __ctx+"/js/javacode/",
  37. onFocus:function(){
  38. InitMirror.toggleFocus(key);
  39. }
  40. });
  41. editor.targetId=$(this).attr("id");
  42. InitMirror.options.editors.push({key:key,editor:editor});
  43. if(InitMirror.options.isCurrent){
  44. InitMirror.editor = editor;
  45. }
  46. InitMirror.options.isCurrent=false;
  47. });
  48. };
  49. //获取编辑器中不重复的key
  50. InitMirror.getKey=function(){
  51. var key = Math.floor(Math.random()*InitMirror.options.randomRange);
  52. for(var i=0,c;c=InitMirror.options.editors[i++];){
  53. if(key==c.key)
  54. return InitMirror.getKey();
  55. else
  56. return key;
  57. }
  58. return key;
  59. };
  60. //切换当前获取焦点的编辑器
  61. InitMirror.toggleFocus=function(key){
  62. //focus的事件注册以后会频繁触发,锁定切换操作避免反复调用本方法
  63. if(InitMirror.options.lock)return;
  64. InitMirror.options.lock=true;
  65. for(var i=0,c;c=InitMirror.options.editors[i++];){
  66. if(c.key==key){
  67. InitMirror.editor=c.editor;
  68. }
  69. }
  70. setTimeout(function(){InitMirror.options.lock=false;},200);
  71. };
  72. //保存编辑器内容
  73. InitMirror.save=function(){
  74. for(var i=0,c;c=InitMirror.options.editors[i++];){
  75. c.editor.save();
  76. }
  77. };
  78. //遍历所有编辑器
  79. InitMirror.each=function(func){
  80. for(var i=0,c;c=InitMirror.options.editors[i++];){
  81. func(c.editor);
  82. }
  83. };
  84. //获取特定id的editor
  85. InitMirror.getById=function(id){
  86. var result = null;
  87. InitMirror.each(function(editor){
  88. if(editor.targetId==id){
  89. result=editor;
  90. }
  91. });
  92. return result;
  93. }