autosave.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. UE.plugin.register('autosave', function (){
  2. var me = this,
  3. //无限循环保护
  4. lastSaveTime = new Date(),
  5. //最小保存间隔时间
  6. MIN_TIME = 20,
  7. //auto save key
  8. saveKey = null;
  9. function save ( editor ) {
  10. var saveData;
  11. if ( new Date() - lastSaveTime < MIN_TIME ) {
  12. return;
  13. }
  14. if ( !editor.hasContents() ) {
  15. //这里不能调用命令来删除, 会造成事件死循环
  16. saveKey && me.removePreferences( saveKey );
  17. return;
  18. }
  19. lastSaveTime = new Date();
  20. editor._saveFlag = null;
  21. saveData = me.body.innerHTML;
  22. if ( editor.fireEvent( "beforeautosave", {
  23. content: saveData
  24. } ) === false ) {
  25. return;
  26. }
  27. me.setPreferences( saveKey, saveData );
  28. editor.fireEvent( "afterautosave", {
  29. content: saveData
  30. } );
  31. }
  32. return {
  33. defaultOptions: {
  34. //默认间隔时间
  35. saveInterval: 500,
  36. enableAutoSave: true
  37. },
  38. bindEvents:{
  39. 'ready':function(){
  40. var _suffix = "-drafts-data",
  41. key = null;
  42. if ( me.key ) {
  43. key = me.key + _suffix;
  44. } else {
  45. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  46. }
  47. //页面地址+编辑器ID 保持唯一
  48. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  49. },
  50. 'contentchange': function () {
  51. if (!me.getOpt('enableAutoSave')) {
  52. return;
  53. }
  54. if ( !saveKey ) {
  55. return;
  56. }
  57. if ( me._saveFlag ) {
  58. window.clearTimeout( me._saveFlag );
  59. }
  60. if ( me.options.saveInterval > 0 ) {
  61. me._saveFlag = window.setTimeout( function () {
  62. save( me );
  63. }, me.options.saveInterval );
  64. } else {
  65. save(me);
  66. }
  67. }
  68. },
  69. commands:{
  70. 'clearlocaldata':{
  71. execCommand:function (cmd, name) {
  72. if ( saveKey && me.getPreferences( saveKey ) ) {
  73. me.removePreferences( saveKey )
  74. }
  75. },
  76. notNeedUndo: true,
  77. ignoreContentChange:true
  78. },
  79. 'getlocaldata':{
  80. execCommand:function (cmd, name) {
  81. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  82. },
  83. notNeedUndo: true,
  84. ignoreContentChange:true
  85. },
  86. 'drafts':{
  87. execCommand:function (cmd, name) {
  88. if ( saveKey ) {
  89. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+domUtils.fillHtml+'</p>';
  90. me.focus(true);
  91. }
  92. },
  93. queryCommandState: function () {
  94. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  95. },
  96. notNeedUndo: true,
  97. ignoreContentChange:true
  98. }
  99. }
  100. }
  101. });