fastadmin filedlist动态渲染动态添加的编辑器---编辑页面的优化

Posted cn-oldboy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fastadmin filedlist动态渲染动态添加的编辑器---编辑页面的优化相关的知识,希望对你有一定的参考价值。

问题

通过fieldlist动态添加的组件,是没法自动渲染的。

关于内置组件的渲染

fa官网也只对10个内置的组件,提供了重新渲染的方法。以下是:十个组件,两种方法。

方法1:全部重新渲染 Form.api.bindevent("form[role=form]")
方法2: 精确渲染 并提供了10个组件精确渲染的方法,如下图

技术图片

如何渲染编辑器组件

1.编辑器一般都是官方提供的收费插件
2.安装插件的时候,插件本身就提供了渲染方法。(我安装的是官方的nkeditor插件)
3.具体的渲染方法,写在publicassetsjsackendaddon.js里
4.从addon.js里复制编辑器插件的渲染方法,写到publicassetsjs equire-form.js里。
5.具体的写法是,跟十个组件同级的地方,添加一个editor方法,内容来自addon.js里编辑器的渲染方法。
6.以后就直接调用这个方法,就能渲染。调用方式:Form.events.editor($("form"));
新增位置
技术图片
新增代码

  editor: function(form){
                if ($(".editor",form).size() > 0) {
                    require([‘nkeditor‘, ‘upload‘], function (Nkeditor, Upload) {
                        var getImageFromClipboard, getImageFromDrop, getFileFromBase64;
                       
                        getImageFromClipboard = function (data) {
                            var i, item;
                            i = 0;
                            while (i < data.clipboardData.items.length) {
                                item = data.clipboardData.items[i];
                                if (item.type.indexOf("image") !== -1) {
                                    return item.getAsFile() || false;
                                }
                                i++;
                            }
                            return false;
                        };
                        getImageFromDrop = function (data) {
                            var i, item, images;
                            i = 0;
                            images = [];
                            while (i < data.dataTransfer.files.length) {
                                item = data.dataTransfer.files[i];
                                if (item.type.indexOf("image") !== -1) {
                                    images.push(item);
                                }
                                i++;
                            }
                            return images;
                        };
                        getFileFromBase64 = function (data, url) {
                            var arr = data.split(‘,‘), mime = arr[0].match(/:(.*?);/)[1],
                                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                            while (n--) {
                                u8arr[n] = bstr.charCodeAt(n);
                            }
                            var filename, suffix;
                            if (typeof url != ‘undefined‘) {
                                var urlArr = url.split(‘.‘);
                                filename = url.substr(url.lastIndexOf(‘/‘) + 1);
                                suffix = urlArr.pop();
                            } else {
                                filename = Math.random().toString(36).substring(5, 15);
                            }
                            console.log(filename);
                            if (!suffix) {
                                suffix = data.substring("data:image/".length, data.indexOf(";base64"));
                            }
        
                            var exp = new RegExp("\\." + suffix + "$", "i");
                            filename = exp.test(filename) ? filename : filename + "." + suffix;
                            var file = new File([u8arr], filename, {type: mime});
                            return file;
                        };
        
                        var getImageFromUrl = function (url, callback, outputFormat) {
                            var canvas = document.createElement(‘CANVAS‘),
                                ctx = canvas.getContext(‘2d‘),
                                img = new Image;
                            img.crossOrigin = ‘Anonymous‘;
                            img.onload = function () {
                                var urlArr = url.split(‘.‘);
                                var suffix = urlArr.pop();
                                suffix = suffix.match(/^(jpg|png|gif|bmp|jpeg)$/i) ? suffix : ‘png‘;
        
                                try {
                                    canvas.height = img.height;
                                    canvas.width = img.width;
                                    ctx.drawImage(img, 0, 0);
                                    var dataURL = canvas.toDataURL(outputFormat || ‘image/‘ + suffix);
                                    var file = getFileFromBase64(dataURL, url);
                                } catch (e) {
                                    callback.call(this, null);
                                }
        
                                callback.call(this, file);
                                canvas = null;
                            };
                            img.onerror = function (e) {
                                callback.call(this, null);
                            };
                            img.src = url;
                        };
                        //上传Word图片
                        Nkeditor.uploadwordimage = function (index, image) {
                            var that = this;
                            (function () {
                                var file = getFileFromBase64(image);
                                var placeholder = new RegExp("##" + index + "##", "g");
                                Upload.api.send(file, function (data) {
                                    that.html(that.html().replace(placeholder, Fast.api.cdnurl(data.url)));
                                }, function (data) {
                                    that.html(that.html().replace(placeholder, ""));
                                });
                            }(index, image));
                        };
        
                        Nkeditor.lang({
                            remoteimage: ‘下载远程图片‘
                        });
                        //远程下载图片
                        Nkeditor.plugin(‘remoteimage‘, function (K) {
                            var editor = this, name = ‘remoteimage‘;
                            editor.plugin.remoteimage = {
                                download: function (e) {
                                    var that = this;
                                    var html = that.html();
                                    var staging = {}, orgined = {}, index = 0, images = 0, completed = 0, failured = 0;
                                    var checkrestore = function () {
                                        if (completed + failured >= images) {
                                            $.each(staging, function (i, j) {
                                                that.html(that.html().replace("<code>" + i + "</code>", j));
                                            });
                                        }
                                    };
                                    html.replace(/<code>([sS]*?)</code>/g, function (code) {
                                            staging[index] = code;
                                            return "<code>" + index + "</code>";
                                        }
                                    );
                                    html = html.replace(/<img([sS]*?)ssrcs*=s*(‘|")((http(s?):)([sS]*?))(‘|")([sS]*?)[/]?>/g, function () {
                                        images++;
                                        var url = arguments[3];
                                        var placeholder = ‘<img src="‘ + Fast.api.cdnurl("/assets/addons/nkeditor/img/downloading.png") + ‘" data-index="‘ + index + ‘" />‘;
                                        //如果是云存储的链接,则忽略
                                        if (Config.upload.cdnurl && url.indexOf(Config.upload.cdnurl) > -1) {
                                            completed++;
                                            return arguments[0];
                                        } else {
                                            orgined[index] = arguments[0];
                                        }
                                        //下载远程图片
                                        (function (index, url, placeholder) {
                                            getImageFromUrl(url, function (file) {
                                                if (!file) {
                                                    failured++;
                                                    that.html(that.html().replace(placeholder, orgined[index]));
                                                    checkrestore();
                                                } else {
                                                    Upload.api.send(file, function (data) {
                                                        completed++;
                                                        that.html(that.html().replace(placeholder, ‘<img src="‘ + Fast.api.cdnurl(data.url) + ‘" />‘));
                                                        checkrestore();
                                                    }, function (data) {
                                                        failured++;
                                                        that.html(that.html().replace(placeholder, orgined[index]));
                                                        checkrestore();
                                                    });
                                                }
                                            });
                                        })(index, url, placeholder);
                                        index++;
                                        return placeholder;
                                    });
                                    if (index > 0) {
                                        that.html(html);
                                    } else {
                                        Toastr.info("没有需要下载的远程图片");
                                    }
                                }
                            };
                            // 点击图标时执行
                            editor.clickToolbar(name, editor.plugin.remoteimage.download);
                        });
        
                        $(".editor", form).each(function () {
                            console.log("开始创建。。。")
                            var that = this;
                            Nkeditor.create(that, {
                                width: ‘100%‘,
                                filterMode: false,
                                wellFormatMode: false,
                                allowMediaUpload: true, //是否允许媒体上传
                                allowFileManager: true,
                                allowImageUpload: true,
                                wordImageServer: typeof Config.nkeditor != ‘undefined‘ && Config.nkeditor.wordimageserver ? "127.0.0.1:10101" : "", //word图片替换服务器的IP和端口
                                urlType: Config.upload.cdnurl ? ‘domain‘ : ‘‘,//给图片加前缀
                                cssPath: Fast.api.cdnurl(‘/assets/addons/nkeditor/plugins/code/prism.css‘),
                                cssData: "body {font-size: 13px}",
                                fillDescAfterUploadImage: false, //是否在上传后继续添加描述信息
                                themeType: typeof Config.nkeditor != ‘undefined‘ ? Config.nkeditor.theme : ‘black‘, //编辑器皮肤,这个值从后台获取
                                fileManagerJson: Fast.api.fixurl("/addons/nkeditor/index/attachment/module/" + Config.modulename),
                                items: [
                                    // ‘source‘, ‘undo‘, ‘redo‘, ‘preview‘, ‘print‘, ‘template‘, ‘code‘, ‘quote‘, ‘cut‘, ‘copy‘, ‘paste‘,
                                    ‘source‘,‘bold‘,‘italic‘, ‘underline‘, ‘strikethrough‘, ‘plainpaste‘, ‘wordpaste‘, ‘justifyleft‘, ‘justifycenter‘, ‘justifyright‘,
                                     ‘insertorderedlist‘, ‘insertunorderedlist‘, ‘subscript‘,
                                    ‘superscript‘,‘image‘, ‘multiimage‘,  ‘table‘, 
                                   ‘fullscreen‘
                                ],
                                afterCreate: function () {
                                    console.log("创建完成。。。")
                                    var self = this;
                                    //Ctrl+回车提交
                                    Nkeditor.ctrl(document, 13, function () {
                                        self.sync();
                                        $(that).closest("form").submit();
                                    });
                                    Nkeditor.ctrl(self.edit.doc, 13, function () {
                                        self.sync();
                                        $(that).closest("form").submit();
                                    });
                                    //粘贴上传
                                    $("body", self.edit.doc).bind(‘paste‘, function (event) {
                                        var image, pasteEvent;
                                        pasteEvent = event.originalEvent;
                                        if (pasteEvent.clipboardData && pasteEvent.clipboardData.items) {
                                            image = getImageFromClipboard(pasteEvent);
                                            if (image) {
                                                event.preventDefault();
                                                Upload.api.send(image, function (data) {
                                                    self.exec("insertimage", Fast.api.cdnurl(data.url));
                                                });
                                            }
                                        }
                                    });
                                    //挺拽上传
                                    $("body", self.edit.doc).bind(‘drop‘, function (event) {
                                        var image, pasteEvent;
                                        pasteEvent = event.originalEvent;
                                        if (pasteEvent.dataTransfer && pasteEvent.dataTransfer.files) {
                                            images = getImageFromDrop(pasteEvent);
                                            if (images.length > 0) {
                                                event.preventDefault();
                                                $.each(images, function (i, image) {
                                                    Upload.api.send(image, function (data) {
                                                        self.exec("insertimage", Fast.api.cdnurl(data.url));
                                                    });
                                                });
                                            }
                                        }
                                    });
                                },
                                //FastAdmin自定义处理
                                beforeUpload: function (callback, file) {
                                    var file = file ? file : $("input.ke-upload-file", this.form).prop(‘files‘)[0];
                                    Upload.api.send(file, function (data) {
                                        var data = {code: ‘000‘, data: {url: Fast.api.cdnurl(data.url)}, title: ‘‘, width: ‘‘, height: ‘‘, border: ‘‘, align: ‘‘};
                                        callback(data);
                                    });
        
                                },
                                //错误处理 handler
                                errorMsgHandler: function (message, type) {
                                    try {
                                        console.log(message, type);
                                    } catch (Error) {
                                        alert(message);
                                    }
                                }
                            });
                        });
                    });
                }
            }

编辑器优化----让编辑器动态的显示,整个编辑页面,只有动态的展示一个编辑器

1.给每个想要展示编辑器的地方,先加上一个class,我定义为myeditor
2.使用JS,为每个myeditor类,动态的添加editor类
以cms中的archives控制器为例,找到publicassetsjsackendcmsarchives.js
在js中的add方法中,添加一些代码。以下为添加位置和具体代码
技术图片

 $(‘body‘).on(‘click‘, ‘.myeditor‘, function(){
                var cunzai = $(this).prev().length > 0
                console.log(cunzai)
               if(cunzai){
                    $(‘.ke-container‘).hide()
                    $(‘.myeditor‘).show()
                    $(this).prev().show()
                    $(this).hide()
               }else{
                      // 让所有的编辑器隐藏,并且显示输入框,
                $(‘.ke-container‘).hide()
                $(‘.myeditor‘).show()
               //  $(‘.myeditor‘).removeClass(‘editor‘)
               //  新增编辑器类
               $(this).addClass(‘editor‘)
               // 添加完成以后,使用先的方法,初始化编辑器,会提示错误  Uncaught TypeError: form.is is not a function
              // Controller.api.bindevent();
               Form.events.editor("form");
               console.log(‘创建完成‘)

               }})
            












以上是关于fastadmin filedlist动态渲染动态添加的编辑器---编辑页面的优化的主要内容,如果未能解决你的问题,请参考以下文章

fastadmin动态添加input渲染

fastadmin动态添加select无法显示问题

fastadmin的动态表设计---这个是基础中的基础

fastadmin 一键生成CRUD-特殊字符-关联字段

fastadmin组件之selectpicker使用方法

fastadmin组件之selectpicker使用方法