代码汇编程王国

Editor.md自动保存插件的开发

2019-02-15  本文已影响14人  代码汇

Markdown编辑器Editor.md自动保存插件的开发。文章编辑器没有自动保存功能怎么行,万一不小心忘记保存不就辛苦白费了,然后就着手给自己的编辑器加了个自动保存功能,分享给有需要的朋友。
原文地址:代码汇个人博客 http://www.codehui.net/info/40.html

自动保存基于localStorage开发,请注意浏览器兼容。(IE7及以下不兼容)。各个浏览器对localStorage的存储大小支持都是不同的,chrome是5M ,IE10是1630K,其他的可以自行测试,基本保存一篇文章绰绰有余了。

1. 插件运行流程

插件使用方法:在编辑区输入内容后,会自动保存内容到客户端本地存储,页面关闭和断电对保存的内容不受影响。保存的内容没有过期时间,直到手动去除。

代码汇

2. 创建插件文件

plugins目录下创建 code-auto-save/code-auto-save.js文件。

3. 页面使用插件

为更方便使用缓存,我们在编辑器的工具栏添加一个自定义的按钮,就和ueditor类似,点击按钮读取缓存内容到编辑器。页面代码如下,都有注释的

<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="utf-8" />
        <title>editormd自动保存插件</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="../css/editormd.css" />
    </head>
    <body>
        <div id="test-editormd">
            <textarea style="display:none;"></textarea>
        </div>
        <script src="js/jquery.min.js"></script>
        <script src="../editormd.js"></script>
        <script type="text/javascript">
            var testEditor = editormd("test-editormd", {
                path: '../lib/',
                // 工具栏添加一个自定义方法
                toolbarIcons: function() {
                    // 给工具栏full模式添加一个自定义方法
                    return editormd.toolbarModes.full.concat(["customIcon"]);
                },
                // 自定义方法的图标 指定一个FontAawsome的图标类
                toolbarIconsClass: {
                    customIcon: "fa-paste"
                },
                // 没有图标可以插入内容,字符串或HTML标签
                toolbarIconTexts: {
                    customIcon: "从草稿箱加载"
                },
                // 图标的title
                lang: {
                    toolbar: {
                        customIcon: "从草稿箱加载"
                    }
                },
                // 自定义工具栏按钮的事件处理
                toolbarHandlers: {
                    customIcon: function(){
                        // 读取缓存内容
                        testEditor.CodeAutoSaveGetCache();
                    }
                },
                // 自定义工具栏按钮的事件处理
                onload: function() {
                    // 引入插件 执行监听方法
                    editormd.loadPlugin("../plugins/code-auto-save/code-auto-save", function() {
                        // 初始化插件 实现监听
                        testEditor.CodeAutoSave();
                    });
                }
            });
            // 删除缓存
            testEditor.CodeAutoSaveDelCache();
            // 清空缓存的文档内容
            testEditor.CodeAutoSaveEmptyCacheContent();
            // 自定义设置缓存
            testEditor.CodeAutoSaveSetCache('缓存内容');
        </script>
    </body>

</html>

4. 插件的内容

防止缓存冲突,将页面url作为存储的key进去区分。监听编辑器change事件最好有一小段时间的缓冲,不然操作缓存太频繁造成性能问题。

/*!
 * editormd图片粘贴上传插件
 *
 * @file   code-auto-save.js
 * @author codehui
 * @date   2018-10-27
 * @link   https://www.codehui.net
 */

(function() {

    var factory = function (exports) {
        // 定义插件名称
        var pluginName   = "code-auto-save";  
        
        // 缓存key
        var cacheKey = 'editormd_cache';
        // 编辑器内容缓存key 替换url中的符号
        var cacheContentKey = ( location.protocol + location.host + location.pathname + location.search ).replace( /[.:?=\/-]/g, '_' );
        // 定义全局变量
        var cm;

        exports.fn.CodeAutoSave = function() {
            // 初始化系统变量
            var _this       = this;
            cm              = _this.cm;
            var settings    = _this.settings;
            var classPrefix = _this.classPrefix;
            var id          = _this.id;   // 编辑器id
            
            // 定时器
            var _saveFlag = null;    
            // 自动保存间隔时间, 单位ms
            var saveInterval = 500;   

            if(typeof(Storage)=="undefined"){
                console.log('对不起,您的浏览器不支持 web 存储。');
                return ;
            }
            
            // 设置编辑器为当前域名+编辑器id
            cacheContentKey = cacheContentKey + "_" + id;
            
            console.log('初始化插件成功');
            
            // 注册change事件
            cm.on('change', function(){
                
                //已经存在定时器关闭 重新开始 防止多次执行
                if(_saveFlag){
                    window.clearTimeout( _saveFlag );
                }
                //定时器的作用是加缓冲
                _saveFlag = window.setTimeout( function () {
                    // 执行设置缓存方法  cm.getValue() 是编辑器的源文档
                    _this.CodeAutoSaveSetCache(cm.getValue());
                }, saveInterval);
            })

        };
        // 设置缓存
        exports.fn.CodeAutoSaveSetCache = function(value) {
            value = value || cm.getValue();
            console.log('设置缓存');
            var cacheContent = {};
            cacheContent[cacheContentKey] = value;
            localStorage.setItem(cacheKey, JSON.stringify(cacheContent));
        }
        
        // 读取缓存
        exports.fn.CodeAutoSaveGetCache = function() {
            // 判断缓存key
            if(localStorage.hasOwnProperty(cacheKey)){
                var cacheData = JSON.parse(localStorage.getItem(cacheKey));
                if(cacheData[cacheContentKey]){
                    console.log('读取缓存 设置文档内容')
                    cm.setValue(cacheData[cacheContentKey]);
                }
            }else{
                console.log('缓存中没有数据')
            }
        }
        
        // 删除缓存
        exports.fn.CodeAutoSaveDelCache = function() {
            console.log('删除缓存')
            localStorage.removeItem(cacheKey);
        }
        
        // 清空缓存的文档内容
        exports.fn.CodeAutoSaveEmptyCacheContent = function() {
            console.log('清除缓存文档内容')
            _this.CodeAutoSaveSetCache('');
        }

    };
    
    // CommonJS/Node.js
    if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
    { 
        module.exports = factory;
    }
    else if (typeof define === "function")  // AMD/CMD/Sea.js
    {
        if (define.amd) { // for Require.js

            define(["editormd"], function(editormd) {
                factory(editormd);
            });

        } else { // for Sea.js
            define(function(require) {
                var editormd = require("./../../editormd");
                factory(editormd);
            });
        }
    } 
    else
    {
        factory(window.editormd);
    }

})();

上一篇下一篇

猜你喜欢

热点阅读